From df588c5be663ed7a9455950d9cf8a0875f9b29ed Mon Sep 17 00:00:00 2001 From: Thomas Kohler Date: Sun, 12 Nov 2023 15:05:46 +0100 Subject: [PATCH] lint: fix issues of errorlint --- .golangci.yml | 55 +-- api/api.go | 46 +-- api/api_test.go | 4 +- api/basic_auth_test.go | 1 + api/cors.go | 12 +- api/cors_test.go | 1 + api/helpers_test.go | 19 +- connection.go | 6 +- device.go | 6 +- doc.go | 9 +- drivers/aio/aio.go | 2 +- drivers/aio/analog_actuator_driver.go | 26 +- drivers/aio/analog_sensor_driver.go | 24 +- drivers/aio/analog_sensor_driver_test.go | 29 +- drivers/aio/grove_drivers.go | 8 +- drivers/aio/grove_drivers_test.go | 7 +- .../aio/grove_temperature_sensor_driver.go | 2 +- .../grove_temperature_sensor_driver_test.go | 12 +- drivers/aio/helpers_test.go | 20 +- drivers/aio/temperature_sensor_driver.go | 9 +- drivers/aio/temperature_sensor_driver_test.go | 29 +- .../common/mfrc522/mfrc522_pcd_register.go | 1 + drivers/common/mfrc522/mfrc522_pcd_test.go | 4 +- drivers/common/mfrc522/mfrc522_picc.go | 5 +- drivers/gpio/aip1640_driver_test.go | 7 +- drivers/gpio/button_driver.go | 69 ++-- drivers/gpio/button_driver_test.go | 1 + drivers/gpio/buzzer_driver.go | 68 ++-- drivers/gpio/buzzer_driver_test.go | 7 +- drivers/gpio/direct_pin_driver.go | 40 +-- drivers/gpio/direct_pin_driver_test.go | 13 +- drivers/gpio/easy_driver.go | 7 + drivers/gpio/gpio_driver.go | 14 +- drivers/gpio/gpio_driver_test.go | 1 + drivers/gpio/grove_drivers_test.go | 7 +- drivers/gpio/hcsr04_driver_test.go | 1 + drivers/gpio/hd44780_driver.go | 56 +-- drivers/gpio/hd44780_driver_test.go | 4 +- drivers/gpio/helpers_test.go | 48 +-- drivers/gpio/led_driver.go | 87 ++--- drivers/gpio/led_driver_test.go | 15 +- drivers/gpio/max7219_driver.go | 1 + drivers/gpio/max7219_driver_test.go | 7 +- drivers/gpio/motor_driver.go | 214 ++++++------ drivers/gpio/motor_driver_test.go | 1 + drivers/gpio/pir_motion_driver.go | 61 ++-- drivers/gpio/pir_motion_driver_test.go | 1 + drivers/gpio/relay_driver.go | 92 ++--- drivers/gpio/relay_driver_test.go | 5 +- drivers/gpio/rgb_led_driver.go | 119 ++++--- drivers/gpio/rgb_led_driver_test.go | 15 +- drivers/gpio/servo_driver.go | 65 ++-- drivers/gpio/servo_driver_test.go | 4 +- drivers/gpio/stepper_driver.go | 9 +- drivers/gpio/tm1638_driver.go | 2 +- drivers/gpio/tm1638_driver_test.go | 7 +- drivers/i2c/adafruit1109_driver.go | 2 +- drivers/i2c/adafruit1109_driver_test.go | 1 + drivers/i2c/adafruit2327_driver_test.go | 1 + drivers/i2c/adafruit2348_driver.go | 9 +- drivers/i2c/adafruit2348_driver_test.go | 1 + drivers/i2c/ads1x15_driver.go | 121 ++++--- drivers/i2c/ads1x15_driver_test.go | 2 + drivers/i2c/adxl345_driver.go | 21 +- drivers/i2c/adxl345_driver_test.go | 11 +- drivers/i2c/bh1750_driver.go | 24 +- drivers/i2c/bh1750_driver_test.go | 1 + drivers/i2c/blinkm_driver.go | 36 +- drivers/i2c/blinkm_driver_test.go | 2 + drivers/i2c/bme280_driver.go | 10 +- drivers/i2c/bme280_driver_test.go | 53 +-- drivers/i2c/bmp180_driver.go | 30 +- drivers/i2c/bmp180_driver_test.go | 28 +- drivers/i2c/bmp280_driver.go | 28 +- drivers/i2c/bmp280_driver_test.go | 12 +- drivers/i2c/bmp388_driver.go | 40 ++- drivers/i2c/bmp388_driver_test.go | 9 +- drivers/i2c/ccs811_driver.go | 26 +- drivers/i2c/ccs811_driver_test.go | 1 + drivers/i2c/drv2605l_driver.go | 36 +- drivers/i2c/drv2605l_driver_test.go | 4 +- drivers/i2c/generic_driver_test.go | 1 + drivers/i2c/grove_drivers_test.go | 13 +- drivers/i2c/grovepi_driver.go | 10 +- drivers/i2c/grovepi_driver_test.go | 5 +- drivers/i2c/helpers_test.go | 54 +-- drivers/i2c/hmc5883l_driver.go | 55 +-- drivers/i2c/hmc5883l_driver_test.go | 1 + drivers/i2c/hmc6352_driver.go | 15 +- drivers/i2c/hmc6352_driver_test.go | 1 + drivers/i2c/i2c_config_test.go | 1 + drivers/i2c/i2c_connection.go | 12 +- drivers/i2c/i2c_connection_test.go | 2 + drivers/i2c/i2c_driver.go | 8 +- drivers/i2c/i2c_driver_test.go | 1 + drivers/i2c/ina3221_driver_test.go | 1 + drivers/i2c/jhd1313m1_driver.go | 135 ++++---- drivers/i2c/jhd1313m1_driver_test.go | 7 +- drivers/i2c/l3gd20h_driver.go | 3 + drivers/i2c/l3gd20h_driver_test.go | 17 +- drivers/i2c/lidarlite_driver.go | 28 +- drivers/i2c/lidarlite_driver_test.go | 7 +- drivers/i2c/mcp23017_driver.go | 80 ++--- drivers/i2c/mcp23017_driver_test.go | 4 +- drivers/i2c/mma7660_driver.go | 4 + drivers/i2c/mma7660_driver_test.go | 11 +- drivers/i2c/mpl115a2_driver.go | 18 +- drivers/i2c/mpl115a2_driver_test.go | 1 + drivers/i2c/mpu6050_driver_test.go | 1 + drivers/i2c/pca9501_driver.go | 9 +- drivers/i2c/pca9501_driver_test.go | 2 + drivers/i2c/pca953x_driver_test.go | 1 + drivers/i2c/pca9685_driver.go | 35 +- drivers/i2c/pca9685_driver_test.go | 1 + drivers/i2c/pcf8583_driver.go | 44 +-- drivers/i2c/pcf8583_driver_test.go | 14 +- drivers/i2c/pcf8591_driver.go | 23 +- drivers/i2c/pcf8591_driver_test.go | 1 + drivers/i2c/sht2x_driver.go | 72 ++-- drivers/i2c/sht2x_driver_test.go | 8 +- drivers/i2c/sht3x_driver.go | 67 ++-- drivers/i2c/sht3x_driver_test.go | 1 + drivers/i2c/ssd1306_driver.go | 59 ++-- drivers/i2c/ssd1306_driver_test.go | 2 + drivers/i2c/th02_driver.go | 5 +- drivers/i2c/th02_driver_test.go | 1 + drivers/i2c/tsl2561_driver.go | 56 +-- drivers/i2c/tsl2561_driver_test.go | 1 + drivers/i2c/wiichuck_driver.go | 4 +- drivers/i2c/wiichuck_driver_test.go | 1 + drivers/i2c/yl40_driver.go | 28 +- drivers/i2c/yl40_driver_test.go | 10 +- drivers/spi/apa102_test.go | 1 + drivers/spi/mcp3002.go | 6 +- drivers/spi/mcp3002_test.go | 1 + drivers/spi/mcp3004.go | 17 +- drivers/spi/mcp3004_test.go | 1 + drivers/spi/mcp3008.go | 17 +- drivers/spi/mcp3008_test.go | 1 + drivers/spi/mcp3202.go | 17 +- drivers/spi/mcp3202_test.go | 1 + drivers/spi/mcp3204.go | 17 +- drivers/spi/mcp3204_test.go | 1 + drivers/spi/mcp3208.go | 17 +- drivers/spi/mcp3208_test.go | 1 + drivers/spi/mcp3304.go | 17 +- drivers/spi/mcp3304_test.go | 1 + drivers/spi/mfrc522_driver_test.go | 1 + drivers/spi/spi_connection_test.go | 1 + drivers/spi/spi_driver.go | 12 +- drivers/spi/spi_driver_test.go | 1 + drivers/spi/ssd1306_driver.go | 2 + drivers/spi/ssd1306_driver_test.go | 37 +- eventer.go | 12 +- examples/batty.go | 14 +- examples/raspi_adafruit2327_servo.go | 20 +- examples/raspi_adafruit2348_dcmotor.go | 24 +- examples/raspi_adafruit2348_stepper.go | 12 +- helpers_test.go | 22 +- master.go | 2 +- master_test.go | 12 +- platforms/adaptors/digitalpinsadaptor.go | 16 +- platforms/adaptors/digitalpinsadaptor_test.go | 4 +- platforms/adaptors/i2cbusadaptor.go | 1 + platforms/adaptors/i2cbusadaptor_test.go | 3 +- platforms/adaptors/pwmpinsadaptor.go | 12 +- platforms/adaptors/pwmpinsadaptor_test.go | 33 +- platforms/adaptors/spibusadaptor.go | 1 + platforms/adaptors/spibusadaptor_test.go | 3 +- platforms/audio/audio_adaptor.go | 13 +- platforms/audio/audio_adaptor_test.go | 7 +- platforms/audio/audio_driver.go | 9 +- platforms/audio/audio_driver_test.go | 3 +- platforms/beaglebone/beaglebone_adaptor.go | 19 +- .../beaglebone/beaglebone_adaptor_test.go | 9 +- platforms/beaglebone/black_pins.go | 29 +- platforms/ble/battery_driver.go | 16 +- platforms/ble/battery_driver_test.go | 1 + platforms/ble/ble_client_adaptor.go | 6 +- platforms/ble/ble_client_adaptor_test.go | 1 + platforms/ble/device_information_driver.go | 31 +- .../ble/device_information_driver_test.go | 1 + platforms/ble/generic_access_driver.go | 1 + platforms/ble/generic_access_driver_test.go | 1 + platforms/ble/helpers_test.go | 26 +- platforms/ble/serial_port.go | 16 +- platforms/chip/chip_adaptor.go | 7 +- platforms/chip/chip_adaptor_test.go | 7 +- platforms/dexter/gopigo3/driver.go | 324 +++++++++--------- platforms/dexter/gopigo3/driver_test.go | 165 +++------ platforms/digispark/digispark_adaptor.go | 40 +-- platforms/digispark/digispark_adaptor_test.go | 4 +- platforms/digispark/digispark_i2c.go | 91 ++--- platforms/digispark/digispark_i2c_test.go | 4 +- platforms/digispark/littleWire.go | 2 +- platforms/dji/tello/crc.go | 1 + platforms/dji/tello/driver.go | 13 +- platforms/dji/tello/driver_test.go | 8 +- platforms/dragonboard/dragonboard_adaptor.go | 1 + .../dragonboard/dragonboard_adaptor_test.go | 5 +- platforms/firmata/ble_firmata_adaptor.go | 3 +- platforms/firmata/ble_firmata_adaptor_test.go | 1 + platforms/firmata/client/client.go | 6 +- platforms/firmata/firmata_adaptor.go | 15 +- platforms/firmata/firmata_adaptor_test.go | 2 + platforms/firmata/firmata_i2c.go | 10 +- platforms/firmata/firmata_i2c_test.go | 2 + platforms/firmata/tcp_firmata_adaptor.go | 14 +- platforms/firmata/tcp_firmata_adaptor_test.go | 1 + platforms/holystone/holystone.go | 2 + platforms/holystone/hs200/hs200_driver.go | 8 +- .../holystone/hs200/hs200_driver_test.go | 1 + platforms/intel-iot/curie/imu_driver.go | 1 + platforms/intel-iot/curie/imu_driver_test.go | 10 +- platforms/intel-iot/edison/edison_adaptor.go | 27 +- .../intel-iot/edison/edison_adaptor_test.go | 53 +-- platforms/intel-iot/joule/joule_adaptor.go | 4 +- .../intel-iot/joule/joule_adaptor_test.go | 7 +- platforms/jetson/jetson_adaptor.go | 7 +- platforms/jetson/jetson_adaptor_test.go | 3 +- platforms/jetson/pwm_pin.go | 2 +- platforms/joystick/joystick_adaptor.go | 8 +- platforms/joystick/joystick_adaptor_test.go | 4 +- platforms/joystick/joystick_driver.go | 6 +- platforms/joystick/joystick_driver_test.go | 8 +- platforms/keyboard/keyboard.go | 20 +- platforms/keyboard/keyboard_driver_test.go | 3 +- platforms/leap/leap_motion_adaptor.go | 16 +- platforms/leap/leap_motion_adaptor_test.go | 1 + platforms/leap/leap_motion_driver.go | 5 +- platforms/leap/leap_motion_driver_test.go | 1 + platforms/mavlink/common/common.go | 1 + platforms/mavlink/common/mavlink.go | 38 +- platforms/mavlink/mavlink_adaptor.go | 19 +- platforms/mavlink/mavlink_adaptor_test.go | 5 +- platforms/mavlink/mavlink_driver.go | 7 +- platforms/mavlink/mavlink_driver_test.go | 2 + platforms/mavlink/mavlink_udp_adaptor.go | 2 +- platforms/mavlink/mavlink_udp_adaptor_test.go | 1 + platforms/megapi/megapi_adaptor.go | 3 +- platforms/megapi/motor_driver.go | 54 +-- platforms/microbit/accelerometer_driver.go | 1 + .../microbit/accelerometer_driver_test.go | 2 + platforms/microbit/button_driver.go | 1 + platforms/microbit/button_driver_test.go | 1 + platforms/microbit/helpers_test.go | 26 +- platforms/microbit/io_pin_driver.go | 3 +- platforms/microbit/io_pin_driver_test.go | 1 + platforms/microbit/led_driver.go | 78 ++--- platforms/microbit/led_driver_test.go | 1 + platforms/microbit/magnetometer_driver.go | 1 + .../microbit/magnetometer_driver_test.go | 2 + platforms/microbit/temperature_driver.go | 1 + platforms/microbit/temperature_driver_test.go | 1 + platforms/mqtt/mqtt_adaptor.go | 7 +- platforms/mqtt/mqtt_adaptor_test.go | 5 +- platforms/mqtt/mqtt_driver.go | 2 + platforms/mqtt/mqtt_driver_test.go | 1 + platforms/nanopi/nanopi_adaptor.go | 7 +- platforms/nanopi/nanopi_adaptor_test.go | 7 +- platforms/nats/nats_adaptor.go | 1 + platforms/nats/nats_adaptor_test.go | 4 +- platforms/nats/nats_driver.go | 2 + platforms/nats/nats_driver_test.go | 1 + platforms/neurosky/neurosky_adaptor.go | 5 +- platforms/neurosky/neurosky_adaptor_test.go | 1 + platforms/neurosky/neurosky_driver.go | 3 +- platforms/neurosky/neurosky_driver_test.go | 2 + platforms/opencv/camera_driver.go | 8 +- platforms/opencv/camera_driver_test.go | 3 +- platforms/opencv/utils_test.go | 1 + platforms/opencv/window_driver.go | 4 +- platforms/opencv/window_driver_test.go | 1 + platforms/parrot/ardrone/ardrone_adaptor.go | 7 +- .../parrot/ardrone/ardrone_adaptor_test.go | 1 + platforms/parrot/ardrone/ardrone_driver.go | 9 +- .../parrot/ardrone/ardrone_driver_test.go | 1 + platforms/parrot/bebop/bebop_adaptor_test.go | 3 +- platforms/parrot/bebop/bebop_driver.go | 12 +- platforms/parrot/bebop/bebop_driver_test.go | 1 + platforms/parrot/bebop/client/client.go | 2 +- platforms/parrot/minidrone/helpers_test.go | 26 +- .../parrot/minidrone/minidrone_driver.go | 5 +- .../parrot/minidrone/minidrone_driver_test.go | 1 + platforms/particle/adaptor.go | 45 ++- platforms/particle/adaptor_test.go | 46 ++- platforms/pebble/doc.go | 3 +- platforms/pebble/pebble_adaptor.go | 8 +- platforms/pebble/pebble_adaptor_test.go | 1 + platforms/pebble/pebble_driver.go | 7 +- platforms/pebble/pebble_driver_test.go | 1 + platforms/raspi/pwm_pin.go | 6 +- platforms/raspi/pwm_pin_test.go | 1 + platforms/raspi/raspi_adaptor.go | 18 +- platforms/raspi/raspi_adaptor_test.go | 3 +- platforms/rockpi/rockpi_adaptor.go | 9 +- platforms/rockpi/rockpi_adaptor_test.go | 1 + platforms/sphero/bb8/bb8_driver_test.go | 1 + platforms/sphero/bb8/helpers_test.go | 26 +- platforms/sphero/ollie/helpers_test.go | 26 +- platforms/sphero/ollie/ollie_driver.go | 19 +- platforms/sphero/ollie/ollie_driver_test.go | 2 + platforms/sphero/sphero_adaptor.go | 20 +- platforms/sphero/sphero_adaptor_test.go | 1 + platforms/sphero/sphero_driver.go | 30 +- platforms/sphero/sphero_driver_test.go | 2 + platforms/sphero/sphero_packets.go | 9 +- platforms/sphero/sprkplus/helpers_test.go | 26 +- .../sphero/sprkplus/sprkplus_driver_test.go | 1 + platforms/tinkerboard/adaptor.go | 7 +- platforms/tinkerboard/adaptor_test.go | 7 +- platforms/upboard/up2/adaptor.go | 1 + platforms/upboard/up2/adaptor_test.go | 7 +- robot.go | 24 +- robot_work.go | 2 +- system/digitalpin_access_test.go | 1 + system/digitalpin_config.go | 2 + system/digitalpin_config_test.go | 1 + system/digitalpin_gpiod.go | 1 + system/digitalpin_gpiod_test.go | 5 +- system/digitalpin_mock.go | 4 +- system/digitalpin_sysfs.go | 18 +- system/digitalpin_sysfs_test.go | 5 +- system/fs.go | 2 +- system/fs_mock.go | 14 +- system/i2c_device.go | 25 +- system/i2c_device_test.go | 2 + system/pwmpin_sysfs.go | 7 +- system/pwmpin_sysfs_test.go | 1 + system/spi_access.go | 10 +- system/spi_gpio.go | 1 + system/spi_mock.go | 5 +- system/syscall.go | 2 + system/syscall_mock.go | 2 + system/system.go | 2 +- system/system_test.go | 1 + utils.go | 7 +- 337 files changed, 2805 insertions(+), 2365 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 465ecde60..cced8fe17 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -34,10 +34,11 @@ run: linters: # currently active linters: # - #INFO [lintersdb] Active 49 linters: [asasalint asciicheck bidichk contextcheck decorder depguard dupword durationcheck errcheck exportloopref - # gocheckcompilerdirectives gochecknoinits gochecksumtype gofmt gofumpt goimports gomoddirectives gomodguard goprintffuncname gosec gosimple govet grouper - # inamedparam ineffassign makezero mirror misspell musttag nilerr nilnil nolintlint nosprintfhostport perfsprint prealloc protogetter reassign revive - # sloglint staticcheck tagalign tenv testableexamples testifylint tparallel unconvert unparam unused wastedassign] + # INFO [lintersdb] Active 64 linters: [asasalint asciicheck bidichk bodyclose containedctx contextcheck decorder depguard dogsled dupword durationcheck + # errcheck errchkjson errorlint exportloopref forcetypeassert gci gocheckcompilerdirectives gochecknoinits gochecksumtype gocritic gofmt gofumpt goimports + # gomoddirectives gomodguard goprintffuncname gosec gosimple govet grouper inamedparam ineffassign lll makezero mirror misspell musttag nakedret nilerr nilnil + # noctx nolintlint nonamedreturns nosprintfhostport perfsprint prealloc predeclared protogetter reassign revive sloglint staticcheck tagalign tenv + # testableexamples testifylint thelper tparallel unconvert unparam unused usestdlibvars wastedassign] enable-all: true @@ -75,39 +76,23 @@ linters: - testpackage # not needed, we use the same name for test package to have access to unexposed items - wrapcheck # not needed (we allow errors from interface methods) - zerologlint # not needed (related to zerolog package) - # important to have - - 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) # 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) - - errchkjson # useful (reduce bugs) - errname # useful for common style - exhaustruct # useful with some exclusions for existing code (e.g. mavlink/common/common.go) - funlen # useful with some tweeks (reduce bugs, simplify code, better understandable code) - - gci # useful (improve readability) - gocognit # useful with some tweeks (better understandable code) - goconst # useful (reduce bugs) - - 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) - gomnd # useful with some exclusions for existing code (e.g. mavlink.go) - 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" - nestif # useful (reduce bugs, simplify code, better understandable code) - nlreturn # more common style, but could become annoying - - noctx # maybe good (show used context explicit) - - predeclared # useful (reduce bugs) - stylecheck # useful with some tweaking (e.g. underscores in names should be allowed - we use it for constants retrieved from C/C++) - tagliatelle # maybe useful with some tweaking or excluding - - thelper # useful - - usestdlibvars # useful - varnamelen # maybe useful with some tweaking, but many findings - whitespace # more common style, but could become annoying - wsl # more common style, but could become annoying @@ -145,6 +130,36 @@ linters-settings: - "and" - "a" + errorlint: + # Default: true + # %v should be used by default over %w, see https://github.com/uber-go/guide/blob/master/style.md#error-wrapping + errorf: false + # Permit more than 1 %w verb, valid per Go 1.20 (Requires errorf:true) + # Default: true + errorf-multi: false + + gci: + # Section configuration to compare against. + # Section names are case-insensitive and may contain parameters in (). + # The default order of sections is `standard > default > custom > blank > dot`, + # If `custom-order` is `true`, it follows the order of `sections` option. + # Default: ["standard", "default"] + sections: + - standard # Standard section: captures all standard packages. + - default # Default section: contains all imports that could not be matched to another section type. + - prefix(gobot.io/x/gobot/) # Custom section: groups all imports with the specified Prefix. + #- blank # Blank section: contains all blank imports. This section is not present unless explicitly enabled. + #- dot # Dot section: contains all dot imports. This section is not present unless explicitly enabled. + # Enable custom order of sections. + # If `true`, make the section order the same as the order of `sections`. + # Default: false + custom-order: true + + gocritic: + disabled-checks: + - assignOp # very opinionated + - appendAssign # mostly used by intention + nolintlint: # Enable to require an explanation of nonzero length after each nolint directive. # Default: false diff --git a/api/api.go b/api/api.go index 448f2f8e2..b0de3dbb4 100644 --- a/api/api.go +++ b/api/api.go @@ -2,7 +2,6 @@ package api import ( "encoding/json" - "errors" "fmt" "log" "net/http" @@ -11,6 +10,7 @@ import ( "time" "github.com/bmizerany/pat" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/api/robeaux" ) @@ -178,12 +178,14 @@ func (a *API) robeaux(res http.ResponseWriter, req *http.Request) { http.Error(res, err.Error(), http.StatusNotFound) return } - t := strings.Split(path, ".") - if t[len(t)-1] == "js" { + split := strings.Split(path, ".") + ext := split[len(split)-1] + switch ext { + case "js": res.Header().Set("Content-Type", "text/javascript; charset=utf-8") - } else if t[len(t)-1] == "css" { + case "css": res.Header().Set("Content-Type", "text/css; charset=utf-8") - } else if t[len(t)-1] == "html" { + case "html": res.Header().Set("Content-Type", "text/html; charset=utf-8") } if _, err := res.Write(buf); err != nil { @@ -269,9 +271,11 @@ func (a *API) robotDeviceEvent(res http.ResponseWriter, req *http.Request) { device := a.master.Robot(req.URL.Query().Get(":robot")). Device(req.URL.Query().Get(":device")) + //nolint:forcetypeassert // no error return value, so there is no better way if event := a.master.Robot(req.URL.Query().Get(":robot")). Device(req.URL.Query().Get(":device")).(gobot.Eventer). Event(req.URL.Query().Get(":event")); len(event) > 0 { + //nolint:forcetypeassert // no error return value, so there is no better way if err := device.(gobot.Eventer).On(event, func(data interface{}) { d, _ := json.Marshal(data) dataChan <- string(d) @@ -345,6 +349,7 @@ func (a *API) executeRobotDeviceCommand(res http.ResponseWriter, req *http.Reque a.writeJSON(map[string]interface{}{"error": err.Error()}, res) } else { a.executeCommand( + //nolint:forcetypeassert // no error return value, so there is no better way a.master.Robot(req.URL.Query().Get(":robot")). Device(req.URL.Query().Get(":device")).(gobot.Commander). Command(req.URL.Query().Get(":command")), @@ -387,7 +392,10 @@ func (a *API) executeCommand(f func(map[string]interface{}) interface{}, // writeJSON writes `j` as JSON in response func (a *API) writeJSON(j interface{}, res http.ResponseWriter) { - data, _ := json.Marshal(j) + data, err := json.Marshal(j) + if err != nil { + panic(err) + } res.Header().Set("Content-Type", "application/json; charset=utf-8") if _, err := res.Write(data); err != nil { panic(err) @@ -401,29 +409,25 @@ func (a *API) Debug() { }) } -func (a *API) jsonRobotFor(name string) (jrobot *gobot.JSONRobot, err error) { +func (a *API) jsonRobotFor(name string) (*gobot.JSONRobot, error) { if robot := a.master.Robot(name); robot != nil { - jrobot = gobot.NewJSONRobot(robot) - } else { - err = errors.New("No Robot found with the name " + name) + return gobot.NewJSONRobot(robot), nil } - return + return nil, fmt.Errorf("No Robot found with the name %s", name) } -func (a *API) jsonDeviceFor(robot string, name string) (jdevice *gobot.JSONDevice, err error) { +func (a *API) jsonDeviceFor(robot string, name string) (*gobot.JSONDevice, error) { if device := a.master.Robot(robot).Device(name); device != nil { - jdevice = gobot.NewJSONDevice(device) - } else { - err = errors.New("No Device found with the name " + name) + return gobot.NewJSONDevice(device), nil } - return + + return nil, fmt.Errorf("No Device found with the name %s", name) } -func (a *API) jsonConnectionFor(robot string, name string) (jconnection *gobot.JSONConnection, err error) { +func (a *API) jsonConnectionFor(robot string, name string) (*gobot.JSONConnection, error) { if connection := a.master.Robot(robot).Connection(name); connection != nil { - jconnection = gobot.NewJSONConnection(connection) - } else { - err = errors.New("No Connection found with the name " + name) + return gobot.NewJSONConnection(connection), nil } - return + + return nil, fmt.Errorf("No Connection found with the name %s", name) } diff --git a/api/api_test.go b/api/api_test.go index 267b11cc4..895f9416c 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert,usestdlibvars,bodyclose,noctx // ok here package api import ( @@ -12,6 +13,7 @@ import ( "time" "github.com/stretchr/testify/assert" + "gobot.io/x/gobot/v2" ) @@ -413,7 +415,7 @@ func TestRobotDeviceEvent(t *testing.T) { data, _ := reader.ReadString('\n') assert.Equal(t, "data: \"event-data\"\n", data) done = true - case <-time.After(100 * time.Millisecond): + case <-time.After(200 * time.Millisecond): t.Error("Not receiving data") done = true } diff --git a/api/basic_auth_test.go b/api/basic_auth_test.go index f00033f0c..4640b03ae 100644 --- a/api/basic_auth_test.go +++ b/api/basic_auth_test.go @@ -1,3 +1,4 @@ +//nolint:usestdlibvars,noctx // ok here package api import ( diff --git a/api/cors.go b/api/cors.go index 1f982ca8a..91c5b9baa 100644 --- a/api/cors.go +++ b/api/cors.go @@ -38,14 +38,14 @@ func AllowRequestsFrom(allowedOrigins ...string) http.HandlerFunc { } // isOriginAllowed returns true if origin matches an allowed origin pattern. -func (c *CORS) isOriginAllowed(origin string) (allowed bool) { +func (c *CORS) isOriginAllowed(origin string) bool { for _, allowedOriginPattern := range c.allowOriginPatterns { - allowed, _ = regexp.MatchString(allowedOriginPattern, origin) + allowed, _ := regexp.MatchString(allowedOriginPattern, origin) if allowed { - return + return true } } - return + return false } // generatePatterns generates regex expression for AllowOrigins @@ -53,8 +53,8 @@ func (c *CORS) generatePatterns() { if c.AllowOrigins != nil { for _, origin := range c.AllowOrigins { pattern := regexp.QuoteMeta(origin) - pattern = strings.Replace(pattern, "\\*", ".*", -1) - pattern = strings.Replace(pattern, "\\?", ".", -1) + pattern = strings.ReplaceAll(pattern, "\\*", ".*") + pattern = strings.ReplaceAll(pattern, "\\?", ".") c.allowOriginPatterns = append(c.allowOriginPatterns, "^"+pattern+"$") } } diff --git a/api/cors_test.go b/api/cors_test.go index cfd60eeb7..86f2dd01a 100644 --- a/api/cors_test.go +++ b/api/cors_test.go @@ -1,3 +1,4 @@ +//nolint:usestdlibvars,noctx // ok here package api import ( diff --git a/api/helpers_test.go b/api/helpers_test.go index 7e77d10f6..e821c8687 100644 --- a/api/helpers_test.go +++ b/api/helpers_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert // ok here package api import ( @@ -28,8 +29,8 @@ type testDriver struct { gobot.Eventer } -func (t *testDriver) Start() (err error) { return } -func (t *testDriver) Halt() (err error) { return } +func (t *testDriver) Start() error { return nil } +func (t *testDriver) Halt() error { return nil } func (t *testDriver) Name() string { return t.name } func (t *testDriver) SetName(n string) { t.name = n } func (t *testDriver) Pin() string { return t.pin } @@ -65,15 +66,15 @@ type testAdaptor struct { } var ( - testAdaptorConnect = func() (err error) { return } - testAdaptorFinalize = func() (err error) { return } + testAdaptorConnect = func() error { return nil } + testAdaptorFinalize = func() error { return nil } ) -func (t *testAdaptor) Finalize() (err error) { return testAdaptorFinalize() } -func (t *testAdaptor) Connect() (err error) { return testAdaptorConnect() } -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 (t *testAdaptor) Finalize() error { return testAdaptorFinalize() } +func (t *testAdaptor) Connect() error { return testAdaptorConnect() } +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 { return &testAdaptor{ diff --git a/connection.go b/connection.go index 75c8c037a..1e8a9bfe4 100644 --- a/connection.go +++ b/connection.go @@ -40,8 +40,9 @@ func (c *Connections) Each(f func(Connection)) { } // Start calls Connect on each Connection in c -func (c *Connections) Start() (err error) { +func (c *Connections) Start() error { log.Println("Starting connections...") + var err error for _, connection := range *c { info := "Starting connection " + connection.Name() @@ -59,7 +60,8 @@ func (c *Connections) Start() (err error) { } // Finalize calls Finalize on each Connection in c -func (c *Connections) Finalize() (err error) { +func (c *Connections) Finalize() error { + var err error for _, connection := range *c { if cerr := connection.Finalize(); cerr != nil { err = multierror.Append(err, cerr) diff --git a/device.go b/device.go index 924a1f7de..b45b0129e 100644 --- a/device.go +++ b/device.go @@ -53,8 +53,9 @@ func (d *Devices) Each(f func(Device)) { } // Start calls Start on each Device in d -func (d *Devices) Start() (err error) { +func (d *Devices) Start() error { log.Println("Starting devices...") + var err error for _, device := range *d { info := "Starting device " + device.Name() @@ -71,7 +72,8 @@ func (d *Devices) Start() (err error) { } // Halt calls Halt on each Device in d -func (d *Devices) Halt() (err error) { +func (d *Devices) Halt() error { + var err error for _, device := range *d { if derr := device.Halt(); derr != nil { err = multierror.Append(err, derr) diff --git a/doc.go b/doc.go index ada79dd42..acd5e0d58 100644 --- a/doc.go +++ b/doc.go @@ -1,9 +1,11 @@ // Copyright 2014-2018 The Hybrid Group. All rights reserved. /* -Package gobot is the primary entrypoint for Gobot (http://gobot.io), a framework for robotics, physical computing, and the Internet of Things written using the Go programming language . +Package gobot is the primary entrypoint for Gobot (http://gobot.io), a framework for robotics, physical computing, and +the Internet of Things written using the Go programming language . -It provides a simple, yet powerful way to create solutions that incorporate multiple, different hardware devices at the same time. +It provides a simple, yet powerful way to create solutions that incorporate multiple, different hardware devices at the +same time. # Classic Gobot @@ -40,7 +42,8 @@ Here is a "Classic Gobot" program that blinks an LED using an Arduino: # 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: +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 diff --git a/drivers/aio/aio.go b/drivers/aio/aio.go index a8d5b339a..3915ec65b 100644 --- a/drivers/aio/aio.go +++ b/drivers/aio/aio.go @@ -28,5 +28,5 @@ type AnalogReader interface { // AnalogWriter interface represents an Adaptor which has AnalogWrite capabilities type AnalogWriter interface { // gobot.Adaptor - AnalogWrite(pin string, val int) (err error) + AnalogWrite(pin string, val int) error } diff --git a/drivers/aio/analog_actuator_driver.go b/drivers/aio/analog_actuator_driver.go index 41b666bfc..bc6a3eb88 100644 --- a/drivers/aio/analog_actuator_driver.go +++ b/drivers/aio/analog_actuator_driver.go @@ -1,6 +1,7 @@ package aio import ( + "log" "strconv" "gobot.io/x/gobot/v2" @@ -32,7 +33,7 @@ func NewAnalogActuatorDriver(a AnalogWriter, pin string) *AnalogActuatorDriver { connection: a, pin: pin, Commander: gobot.NewCommander(), - scale: func(input float64) (value int) { return int(input) }, + scale: func(input float64) int { return int(input) }, } d.AddCommand("Write", func(params map[string]interface{}) interface{} { @@ -52,10 +53,10 @@ func NewAnalogActuatorDriver(a AnalogWriter, pin string) *AnalogActuatorDriver { } // Start starts driver -func (a *AnalogActuatorDriver) Start() (err error) { return } +func (a *AnalogActuatorDriver) Start() error { return nil } // Halt is for halt -func (a *AnalogActuatorDriver) Halt() (err error) { return } +func (a *AnalogActuatorDriver) Halt() error { return nil } // Name returns the drivers name func (a *AnalogActuatorDriver) Name() string { return a.name } @@ -67,10 +68,17 @@ func (a *AnalogActuatorDriver) SetName(n string) { a.name = n } func (a *AnalogActuatorDriver) Pin() string { return a.pin } // Connection returns the drivers Connection -func (a *AnalogActuatorDriver) Connection() gobot.Connection { return a.connection.(gobot.Connection) } +func (a *AnalogActuatorDriver) Connection() gobot.Connection { + if conn, ok := a.connection.(gobot.Connection); ok { + return conn + } + + log.Printf("%s has no gobot connection\n", a.name) + return nil +} // RawWrite write the given raw value to the actuator -func (a *AnalogActuatorDriver) RawWrite(val int) (err error) { +func (a *AnalogActuatorDriver) RawWrite(val int) error { a.lastRawValue = val return a.connection.AnalogWrite(a.Pin(), val) } @@ -81,19 +89,19 @@ func (a *AnalogActuatorDriver) SetScaler(scaler func(float64) int) { } // Write writes the given value to the actuator -func (a *AnalogActuatorDriver) Write(val float64) (err error) { +func (a *AnalogActuatorDriver) Write(val float64) error { a.lastValue = val rawValue := a.scale(val) return a.RawWrite(rawValue) } // RawValue returns the last written raw value -func (a *AnalogActuatorDriver) RawValue() (val int) { +func (a *AnalogActuatorDriver) RawValue() int { return a.lastRawValue } // Value returns the last written value -func (a *AnalogActuatorDriver) Value() (val float64) { +func (a *AnalogActuatorDriver) Value() float64 { return a.lastValue } @@ -101,7 +109,7 @@ func (a *AnalogActuatorDriver) Value() (val float64) { func AnalogActuatorLinearScaler(fromMin, fromMax float64, toMin, toMax int) func(input float64) (value int) { m := float64(toMax-toMin) / (fromMax - fromMin) n := float64(toMin) - m*fromMin - return func(input float64) (value int) { + return func(input float64) int { if input <= fromMin { return toMin } diff --git a/drivers/aio/analog_sensor_driver.go b/drivers/aio/analog_sensor_driver.go index 81abba4af..7e9059ad3 100644 --- a/drivers/aio/analog_sensor_driver.go +++ b/drivers/aio/analog_sensor_driver.go @@ -1,6 +1,7 @@ package aio import ( + "log" "sync" "time" @@ -44,7 +45,7 @@ func NewAnalogSensorDriver(a AnalogReader, pin string, v ...time.Duration) *Anal Commander: gobot.NewCommander(), interval: 10 * time.Millisecond, halt: make(chan bool), - scale: func(input int) (value float64) { return float64(input) }, + scale: func(input int) float64 { return float64(input) }, mutex: &sync.Mutex{}, } @@ -75,10 +76,10 @@ func NewAnalogSensorDriver(a AnalogReader, pin string, v ...time.Duration) *Anal // Data int - Event is emitted on change and represents the current raw reading from the sensor. // Value float64 - Event is emitted on change and represents the current reading from the sensor. // Error error - Event is emitted on error reading from the sensor. -func (a *AnalogSensorDriver) Start() (err error) { +func (a *AnalogSensorDriver) Start() error { if a.interval == 0 { // cyclic reading deactivated - return + return nil } oldRawValue := 0 oldValue := 0.0 @@ -109,17 +110,17 @@ func (a *AnalogSensorDriver) Start() (err error) { } } }() - return + return nil } // Halt stops polling the analog sensor for new information -func (a *AnalogSensorDriver) Halt() (err error) { +func (a *AnalogSensorDriver) Halt() error { if a.interval == 0 { // cyclic reading deactivated - return + return nil } a.halt <- true - return + return nil } // Name returns the AnalogSensorDrivers name @@ -132,7 +133,14 @@ func (a *AnalogSensorDriver) SetName(n string) { a.name = n } func (a *AnalogSensorDriver) Pin() string { return a.pin } // Connection returns the AnalogSensorDrivers Connection -func (a *AnalogSensorDriver) Connection() gobot.Connection { return a.connection.(gobot.Connection) } +func (a *AnalogSensorDriver) Connection() gobot.Connection { + if conn, ok := a.connection.(gobot.Connection); ok { + return conn + } + + log.Printf("%s has no gobot connection\n", a.name) + return nil +} // Read returns the current reading from the sensor, scaled by the current scaler func (a *AnalogSensorDriver) Read() (float64, error) { diff --git a/drivers/aio/analog_sensor_driver_test.go b/drivers/aio/analog_sensor_driver_test.go index 3e4bff255..3f782e3b9 100644 --- a/drivers/aio/analog_sensor_driver_test.go +++ b/drivers/aio/analog_sensor_driver_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert // ok here package aio import ( @@ -8,6 +9,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -28,9 +30,8 @@ func TestAnalogSensorDriver(t *testing.T) { assert.Equal(t, "42", d.Pin()) assert.Equal(t, 30*time.Second, d.interval) - a.analogReadFunc = func() (val int, err error) { - val = 100 - return + a.analogReadFunc = func() (int, error) { + return 100, nil } ret := d.Command("ReadRaw")(nil).(map[string]interface{}) @@ -44,9 +45,8 @@ func TestAnalogSensorDriver(t *testing.T) { // refresh value on read a = newAioTestAdaptor() d = NewAnalogSensorDriver(a, "3") - a.analogReadFunc = func() (val int, err error) { - val = 150 - return + a.analogReadFunc = func() (int, error) { + return 150, nil } assert.InDelta(t, 0.0, d.Value(), 0.0) val, err := d.Read() @@ -80,7 +80,7 @@ func TestAnalogSensorDriverWithLinearScaler(t *testing.T) { t.Run(name, func(t *testing.T) { // arrange d.SetScaler(AnalogSensorLinearScaler(0, 255, tt.toMin, tt.toMax)) - a.analogReadFunc = func() (val int, err error) { + a.analogReadFunc = func() (int, error) { return tt.input, nil } // act @@ -110,9 +110,8 @@ func TestAnalogSensorDriverStart(t *testing.T) { }) // send data - a.analogReadFunc = func() (val int, err error) { - val = 100 - return + a.analogReadFunc = func() (int, error) { + return 100, nil } require.NoError(t, d.Start()) @@ -130,9 +129,8 @@ func TestAnalogSensorDriverStart(t *testing.T) { }) // send error - a.analogReadFunc = func() (val int, err error) { - err = errors.New("read error") - return + a.analogReadFunc = func() (int, error) { + return 0, errors.New("read error") } select { @@ -150,9 +148,8 @@ func TestAnalogSensorDriverStart(t *testing.T) { sem <- true }) - a.analogReadFunc = func() (val int, err error) { - val = 200 - return + a.analogReadFunc = func() (int, error) { + return 200, nil } d.halt <- true diff --git a/drivers/aio/grove_drivers.go b/drivers/aio/grove_drivers.go index df6c776dc..8d4783420 100644 --- a/drivers/aio/grove_drivers.go +++ b/drivers/aio/grove_drivers.go @@ -63,7 +63,11 @@ type GrovePiezoVibrationSensorDriver struct { // Adds the following API Commands: // // "Read" - See AnalogSensor.Read -func NewGrovePiezoVibrationSensorDriver(a AnalogReader, pin string, v ...time.Duration) *GrovePiezoVibrationSensorDriver { +func NewGrovePiezoVibrationSensorDriver( + a AnalogReader, + pin string, + v ...time.Duration, +) *GrovePiezoVibrationSensorDriver { sensor := &GrovePiezoVibrationSensorDriver{ AnalogSensorDriver: NewAnalogSensorDriver(a, pin, v...), } @@ -71,7 +75,7 @@ func NewGrovePiezoVibrationSensorDriver(a AnalogReader, pin string, v ...time.Du sensor.AddEvent(Vibration) if err := sensor.On(sensor.Event(Data), func(data interface{}) { - if data.(int) > 1000 { + if data.(int) > 1000 { //nolint:forcetypeassert // no error return value, so there is no better way sensor.Publish(sensor.Event(Vibration), data) } }); err != nil { diff --git a/drivers/aio/grove_drivers_test.go b/drivers/aio/grove_drivers_test.go index df88e2cb7..a58502fd1 100644 --- a/drivers/aio/grove_drivers_test.go +++ b/drivers/aio/grove_drivers_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert // ok here package aio import ( @@ -9,6 +10,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -85,9 +87,8 @@ func TestDriverPublishesError(t *testing.T) { for _, driver := range drivers { sem := make(chan struct{}, 1) // send error - testAdaptor.analogReadFunc = func() (val int, err error) { - err = errors.New("read error") - return + testAdaptor.analogReadFunc = func() (int, error) { + return 0, errors.New("read error") } require.NoError(t, driver.Start()) diff --git a/drivers/aio/grove_temperature_sensor_driver.go b/drivers/aio/grove_temperature_sensor_driver.go index 78304a110..f12e5132d 100644 --- a/drivers/aio/grove_temperature_sensor_driver.go +++ b/drivers/aio/grove_temperature_sensor_driver.go @@ -39,6 +39,6 @@ func NewGroveTemperatureSensorDriver(a AnalogReader, pin string, v ...time.Durat } // Temperature returns the last read temperature from the sensor. -func (t *TemperatureSensorDriver) Temperature() (val float64) { +func (t *TemperatureSensorDriver) Temperature() float64 { return t.Value() } diff --git a/drivers/aio/grove_temperature_sensor_driver_test.go b/drivers/aio/grove_temperature_sensor_driver_test.go index a7b303e58..ebe27a278 100644 --- a/drivers/aio/grove_temperature_sensor_driver_test.go +++ b/drivers/aio/grove_temperature_sensor_driver_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert // ok here package aio import ( @@ -8,6 +9,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -41,9 +43,8 @@ func TestGroveTemperatureSensorDriverScaling(t *testing.T) { for name, tt := range tests { t.Run(name, func(t *testing.T) { // arrange - a.analogReadFunc = func() (val int, err error) { - val = tt.input - return + a.analogReadFunc = func() (int, error) { + return tt.input, nil } // act got, err := d.Read() @@ -59,9 +60,8 @@ func TestGroveTempSensorPublishesTemperatureInCelsius(t *testing.T) { a := newAioTestAdaptor() d := NewGroveTemperatureSensorDriver(a, "1") - a.analogReadFunc = func() (val int, err error) { - val = 585 - return + a.analogReadFunc = func() (int, error) { + return 585, nil } _ = d.Once(d.Event(Value), func(data interface{}) { assert.Equal(t, "31.62", fmt.Sprintf("%.2f", data.(float64))) diff --git a/drivers/aio/helpers_test.go b/drivers/aio/helpers_test.go index 38ab5c2db..af7013332 100644 --- a/drivers/aio/helpers_test.go +++ b/drivers/aio/helpers_test.go @@ -7,7 +7,7 @@ type aioTestAdaptor struct { port string mtx sync.Mutex analogReadFunc func() (val int, err error) - analogWriteFunc func(val int) (err error) + analogWriteFunc func(val int) error written []int } @@ -15,10 +15,10 @@ func newAioTestAdaptor() *aioTestAdaptor { t := aioTestAdaptor{ name: "aio_test_adaptor", port: "/dev/null", - analogReadFunc: func() (val int, err error) { + analogReadFunc: func() (int, error) { return 99, nil }, - analogWriteFunc: func(val int) (err error) { + analogWriteFunc: func(val int) error { return nil }, } @@ -27,22 +27,22 @@ func newAioTestAdaptor() *aioTestAdaptor { } // AnalogRead capabilities (interface AnalogReader) -func (t *aioTestAdaptor) AnalogRead(pin string) (val int, err error) { +func (t *aioTestAdaptor) AnalogRead(pin string) (int, error) { t.mtx.Lock() defer t.mtx.Unlock() return t.analogReadFunc() } // AnalogWrite capabilities (interface AnalogWriter) -func (t *aioTestAdaptor) AnalogWrite(pin string, val int) (err error) { +func (t *aioTestAdaptor) AnalogWrite(pin string, val int) error { t.mtx.Lock() defer t.mtx.Unlock() t.written = append(t.written, val) return t.analogWriteFunc(val) } -func (t *aioTestAdaptor) Connect() (err error) { return } -func (t *aioTestAdaptor) Finalize() (err error) { return } -func (t *aioTestAdaptor) Name() string { return t.name } -func (t *aioTestAdaptor) SetName(n string) { t.name = n } -func (t *aioTestAdaptor) Port() string { return t.port } +func (t *aioTestAdaptor) Connect() error { return nil } +func (t *aioTestAdaptor) Finalize() error { return nil } +func (t *aioTestAdaptor) Name() string { return t.name } +func (t *aioTestAdaptor) SetName(n string) { t.name = n } +func (t *aioTestAdaptor) Port() string { return t.port } diff --git a/drivers/aio/temperature_sensor_driver.go b/drivers/aio/temperature_sensor_driver.go index 55c5484c0..15953a04e 100644 --- a/drivers/aio/temperature_sensor_driver.go +++ b/drivers/aio/temperature_sensor_driver.go @@ -68,9 +68,14 @@ func (t *TemperatureSensorDriver) SetLinearScaler(fromMin, fromMax int, toMin, t // If the thermistor is connected to ground, the reverse flag must be set to true. // This means the voltage decreases when temperature gets higher. // Currently no negative values for voltage are supported. -func TemperatureSensorNtcScaler(vRef uint, rOhm uint, reverse bool, ntc TemperatureSensorNtcConf) func(input int) (value float64) { +func TemperatureSensorNtcScaler( + vRef uint, + rOhm uint, + reverse bool, + ntc TemperatureSensorNtcConf, +) func(input int) (value float64) { ntc.initialize() - return (func(input int) (value float64) { + return (func(input int) float64 { if input < 0 { input = 0 } diff --git a/drivers/aio/temperature_sensor_driver_test.go b/drivers/aio/temperature_sensor_driver_test.go index 21c16711b..f0977562a 100644 --- a/drivers/aio/temperature_sensor_driver_test.go +++ b/drivers/aio/temperature_sensor_driver_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert // ok here package aio import ( @@ -42,9 +43,8 @@ func TestTemperatureSensorDriverNtcScaling(t *testing.T) { for name, tt := range tests { t.Run(name, func(t *testing.T) { // arrange - a.analogReadFunc = func() (val int, err error) { - val = tt.input - return + a.analogReadFunc = func() (int, error) { + return tt.input, nil } // act got, err := d.Read() @@ -77,9 +77,8 @@ func TestTemperatureSensorDriverLinearScaling(t *testing.T) { for name, tt := range tests { t.Run(name, func(t *testing.T) { // arrange - a.analogReadFunc = func() (val int, err error) { - val = tt.input - return + a.analogReadFunc = func() (int, error) { + return tt.input, nil } // act got, err := d.Read() @@ -97,9 +96,8 @@ func TestTempSensorPublishesTemperatureInCelsius(t *testing.T) { 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.analogReadFunc = func() (val int, err error) { - val = 585 - return + a.analogReadFunc = func() (int, error) { + return 585, nil } _ = d.Once(d.Event(Value), func(data interface{}) { assert.Equal(t, "31.62", fmt.Sprintf("%.2f", data.(float64))) @@ -122,9 +120,8 @@ func TestTempSensorPublishesError(t *testing.T) { d := NewTemperatureSensorDriver(a, "1") // send error - a.analogReadFunc = func() (val int, err error) { - err = errors.New("read error") - return + a.analogReadFunc = func() (int, error) { + return 0, errors.New("read error") } require.NoError(t, d.Start()) @@ -195,11 +192,15 @@ func TestTempDriver_initialize(t *testing.T) { }, "T1_low": { input: TemperatureSensorNtcConf{TC0: 25, R0: 2500.0, TC1: -13, R1: 10000}, - want: TemperatureSensorNtcConf{TC0: 25, R0: 2500.0, TC1: -13, R1: 10000, B: 2829.6355560320544, t0: 298.15, r: 9.490644159087891}, + want: TemperatureSensorNtcConf{ + TC0: 25, R0: 2500.0, TC1: -13, R1: 10000, B: 2829.6355560320544, t0: 298.15, r: 9.490644159087891, + }, }, "T1_high": { input: TemperatureSensorNtcConf{TC0: 25, R0: 2500.0, TC1: 100, R1: 371}, - want: TemperatureSensorNtcConf{TC0: 25, R0: 2500.0, TC1: 100, R1: 371, B: 2830.087381913779, t0: 298.15, r: 9.49215959052081}, + want: TemperatureSensorNtcConf{ + TC0: 25, R0: 2500.0, TC1: 100, R1: 371, B: 2830.087381913779, t0: 298.15, r: 9.49215959052081, + }, }, } for name, tt := range tests { diff --git a/drivers/common/mfrc522/mfrc522_pcd_register.go b/drivers/common/mfrc522/mfrc522_pcd_register.go index 042e145aa..ea5cec8e6 100644 --- a/drivers/common/mfrc522/mfrc522_pcd_register.go +++ b/drivers/common/mfrc522/mfrc522_pcd_register.go @@ -1,3 +1,4 @@ +//nolint:lll // ok here package mfrc522 // Page 0: Command and status diff --git a/drivers/common/mfrc522/mfrc522_pcd_test.go b/drivers/common/mfrc522/mfrc522_pcd_test.go index 435a2ee81..19c14bf16 100644 --- a/drivers/common/mfrc522/mfrc522_pcd_test.go +++ b/drivers/common/mfrc522/mfrc522_pcd_test.go @@ -56,7 +56,9 @@ func TestNewMFRC522Common(t *testing.T) { func TestInitialize(t *testing.T) { // arrange wantSoftReset := []byte{0x01, 0x0F, 0x01} - wantInit := []byte{0x12, 0x00, 0x13, 0x00, 0x24, 0x26, 0x2A, 0x8F, 0x2B, 0xFF, 0x2D, 0xE8, 0x2C, 0x03, 0x15, 0x40, 0x11, 0x29} + wantInit := []byte{ + 0x12, 0x00, 0x13, 0x00, 0x24, 0x26, 0x2A, 0x8F, 0x2B, 0xFF, 0x2D, 0xE8, 0x2C, 0x03, 0x15, 0x40, 0x11, 0x29, + } wantAntennaOn := []byte{0x14, 0x14, 0x03} wantGain := []byte{0x26, 0x50} c := &busConnMock{} diff --git a/drivers/common/mfrc522/mfrc522_picc.go b/drivers/common/mfrc522/mfrc522_picc.go index 32d2bae2f..1776daa25 100644 --- a/drivers/common/mfrc522/mfrc522_picc.go +++ b/drivers/common/mfrc522/mfrc522_picc.go @@ -1,3 +1,4 @@ +//nolint:lll // ok here package mfrc522 import ( @@ -117,14 +118,14 @@ func (d *MFRC522Common) ReadText() (string, error) { content = append(content, blockData...) } if piccDebug { - fmt.Println("content:", string(content[:]), content) + fmt.Println("content:", string(content), content) } if err := d.piccHalt(); err != nil { return "", err } - return string(content[:]), d.stopCrypto1() + return string(content), d.stopCrypto1() } // WriteText writes the given string to the card. All old values will be overwritten. diff --git a/drivers/gpio/aip1640_driver_test.go b/drivers/gpio/aip1640_driver_test.go index b4870e18c..a820dd00e 100644 --- a/drivers/gpio/aip1640_driver_test.go +++ b/drivers/gpio/aip1640_driver_test.go @@ -6,15 +6,16 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) var _ gobot.Driver = (*AIP1640Driver)(nil) // --------- HELPERS -func initTestAIP1640Driver() (driver *AIP1640Driver) { - driver, _ = initTestAIP1640DriverWithStubbedAdaptor() - return +func initTestAIP1640Driver() *AIP1640Driver { + d, _ := initTestAIP1640DriverWithStubbedAdaptor() + return d } func initTestAIP1640DriverWithStubbedAdaptor() (*AIP1640Driver, *gpioTestAdaptor) { diff --git a/drivers/gpio/button_driver.go b/drivers/gpio/button_driver.go index 72c62d320..509156983 100644 --- a/drivers/gpio/button_driver.go +++ b/drivers/gpio/button_driver.go @@ -24,7 +24,8 @@ type ButtonDriver struct { // // time.Duration: Interval at which the ButtonDriver is polled for new information func NewButtonDriver(a DigitalReader, pin string, v ...time.Duration) *ButtonDriver { - b := &ButtonDriver{ + //nolint:forcetypeassert // no error return value, so there is no better way + d := &ButtonDriver{ Driver: NewDriver(a.(gobot.Connection), "Button"), Eventer: gobot.NewEventer(), pin: pin, @@ -33,39 +34,39 @@ func NewButtonDriver(a DigitalReader, pin string, v ...time.Duration) *ButtonDri interval: 10 * time.Millisecond, halt: make(chan bool), } - b.afterStart = b.initialize - b.beforeHalt = b.shutdown + d.afterStart = d.initialize + d.beforeHalt = d.shutdown if len(v) > 0 { - b.interval = v[0] + d.interval = v[0] } - b.AddEvent(ButtonPush) - b.AddEvent(ButtonRelease) - b.AddEvent(Error) + d.AddEvent(ButtonPush) + d.AddEvent(ButtonRelease) + d.AddEvent(Error) - return b + return d } // Pin returns the ButtonDrivers pin -func (b *ButtonDriver) Pin() string { return b.pin } +func (d *ButtonDriver) Pin() string { return d.pin } // Active gets the current state -func (b *ButtonDriver) Active() bool { +func (d *ButtonDriver) Active() bool { // ensure that read and write can not interfere - b.mutex.Lock() - defer b.mutex.Unlock() + d.mutex.Lock() + defer d.mutex.Unlock() - return b.active + return d.active } // SetDefaultState for the next start. -func (b *ButtonDriver) SetDefaultState(s int) { +func (d *ButtonDriver) SetDefaultState(s int) { // ensure that read and write can not interfere - b.mutex.Lock() - defer b.mutex.Unlock() + d.mutex.Lock() + defer d.mutex.Unlock() - b.defaultState = s + d.defaultState = s } // initialize the ButtonDriver and polls the state of the button at the given interval. @@ -75,20 +76,20 @@ func (b *ButtonDriver) SetDefaultState(s int) { // Push int - On button push // Release int - On button release // Error error - On button error -func (b *ButtonDriver) initialize() error { - state := b.defaultState +func (d *ButtonDriver) initialize() error { + state := d.defaultState go func() { for { - newValue, err := b.connection.(DigitalReader).DigitalRead(b.Pin()) + newValue, err := d.connection.(DigitalReader).DigitalRead(d.Pin()) if err != nil { - b.Publish(Error, err) + d.Publish(Error, err) } else if newValue != state && newValue != -1 { state = newValue - b.update(newValue) + d.update(newValue) } select { - case <-time.After(b.interval): - case <-b.halt: + case <-time.After(d.interval): + case <-d.halt: return } } @@ -96,21 +97,21 @@ func (b *ButtonDriver) initialize() error { return nil } -func (b *ButtonDriver) shutdown() error { - b.halt <- true +func (d *ButtonDriver) shutdown() error { + d.halt <- true return nil } -func (b *ButtonDriver) update(newValue int) { +func (d *ButtonDriver) update(newValue int) { // ensure that read and write can not interfere - b.mutex.Lock() - defer b.mutex.Unlock() + d.mutex.Lock() + defer d.mutex.Unlock() - if newValue != b.defaultState { - b.active = true - b.Publish(ButtonPush, newValue) + if newValue != d.defaultState { + d.active = true + d.Publish(ButtonPush, newValue) } else { - b.active = false - b.Publish(ButtonRelease, newValue) + d.active = false + d.Publish(ButtonRelease, newValue) } } diff --git a/drivers/gpio/button_driver_test.go b/drivers/gpio/button_driver_test.go index a71dcd371..9503b48e2 100644 --- a/drivers/gpio/button_driver_test.go +++ b/drivers/gpio/button_driver_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/gpio/buzzer_driver.go b/drivers/gpio/buzzer_driver.go index 5d1073d46..333985678 100644 --- a/drivers/gpio/buzzer_driver.go +++ b/drivers/gpio/buzzer_driver.go @@ -1,6 +1,7 @@ package gpio import ( + "log" "time" "gobot.io/x/gobot/v2" @@ -152,76 +153,79 @@ func NewBuzzerDriver(a DigitalWriter, pin string) *BuzzerDriver { } // Start implements the Driver interface -func (l *BuzzerDriver) Start() (err error) { return } +func (d *BuzzerDriver) Start() error { return nil } // Halt implements the Driver interface -func (l *BuzzerDriver) Halt() (err error) { return } +func (d *BuzzerDriver) Halt() error { return nil } // Name returns the BuzzerDrivers name -func (l *BuzzerDriver) Name() string { return l.name } +func (d *BuzzerDriver) Name() string { return d.name } // SetName sets the BuzzerDrivers name -func (l *BuzzerDriver) SetName(n string) { l.name = n } +func (d *BuzzerDriver) SetName(n string) { d.name = n } // Pin returns the BuzzerDrivers name -func (l *BuzzerDriver) Pin() string { return l.pin } +func (d *BuzzerDriver) Pin() string { return d.pin } // Connection returns the BuzzerDrivers Connection -func (l *BuzzerDriver) Connection() gobot.Connection { - return l.connection.(gobot.Connection) +func (d *BuzzerDriver) Connection() gobot.Connection { + if conn, ok := d.connection.(gobot.Connection); ok { + return conn + } + + log.Printf("%s has no gobot connection\n", d.name) + return nil } // State return true if the buzzer is On and false if the led is Off -func (l *BuzzerDriver) State() bool { - return l.high +func (d *BuzzerDriver) State() bool { + return d.high } // On sets the buzzer to a high state. -func (l *BuzzerDriver) On() (err error) { - if err = l.connection.DigitalWrite(l.Pin(), 1); err != nil { - return +func (d *BuzzerDriver) On() error { + if err := d.connection.DigitalWrite(d.Pin(), 1); err != nil { + return err } - l.high = true - return + d.high = true + return nil } // Off sets the buzzer to a low state. -func (l *BuzzerDriver) Off() (err error) { - if err = l.connection.DigitalWrite(l.Pin(), 0); err != nil { - return +func (d *BuzzerDriver) Off() error { + if err := d.connection.DigitalWrite(d.Pin(), 0); err != nil { + return err } - l.high = false - return + d.high = false + return nil } // Toggle sets the buzzer to the opposite of it's current state -func (l *BuzzerDriver) Toggle() (err error) { - if l.State() { - err = l.Off() - } else { - err = l.On() +func (d *BuzzerDriver) Toggle() error { + if d.State() { + return d.Off() } - return + return d.On() } // Tone is to make a sound with the given frequency -func (l *BuzzerDriver) Tone(hz, duration float64) (err error) { +func (d *BuzzerDriver) Tone(hz, duration float64) error { // calculation based off https://www.arduino.cc/en/Tutorial/Melody tone := (1.0 / (2.0 * hz)) * 1000000.0 - tempo := ((60 / l.BPM) * (duration * 1000)) + tempo := ((60 / d.BPM) * (duration * 1000)) for i := 0.0; i < tempo*1000; i += tone * 2.0 { - if err = l.On(); err != nil { - return + if err := d.On(); err != nil { + return err } time.Sleep(time.Duration(tone) * time.Microsecond) - if err = l.Off(); err != nil { - return + if err := d.Off(); err != nil { + return err } time.Sleep(time.Duration(tone) * time.Microsecond) } - return + return nil } diff --git a/drivers/gpio/buzzer_driver_test.go b/drivers/gpio/buzzer_driver_test.go index 7f3d34040..f3626a185 100644 --- a/drivers/gpio/buzzer_driver_test.go +++ b/drivers/gpio/buzzer_driver_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -54,7 +55,7 @@ func TestBuzzerDriverTone(t *testing.T) { func TestBuzzerDriverOnError(t *testing.T) { a := newGpioTestAdaptor() d := initTestBuzzerDriver(a) - a.digitalWriteFunc = func(string, byte) (err error) { + a.digitalWriteFunc = func(string, byte) error { return errors.New("write error") } @@ -64,7 +65,7 @@ func TestBuzzerDriverOnError(t *testing.T) { func TestBuzzerDriverOffError(t *testing.T) { a := newGpioTestAdaptor() d := initTestBuzzerDriver(a) - a.digitalWriteFunc = func(string, byte) (err error) { + a.digitalWriteFunc = func(string, byte) error { return errors.New("write error") } @@ -74,7 +75,7 @@ func TestBuzzerDriverOffError(t *testing.T) { func TestBuzzerDriverToneError(t *testing.T) { a := newGpioTestAdaptor() d := initTestBuzzerDriver(a) - a.digitalWriteFunc = func(string, byte) (err error) { + a.digitalWriteFunc = func(string, byte) error { return errors.New("write error") } diff --git a/drivers/gpio/direct_pin_driver.go b/drivers/gpio/direct_pin_driver.go index ebec0ca2b..65afdcf26 100644 --- a/drivers/gpio/direct_pin_driver.go +++ b/drivers/gpio/direct_pin_driver.go @@ -63,61 +63,61 @@ func (d *DirectPinDriver) Pin() string { return d.pin } func (d *DirectPinDriver) Connection() gobot.Connection { return d.connection } // Start implements the Driver interface -func (d *DirectPinDriver) Start() (err error) { return } +func (d *DirectPinDriver) Start() error { return nil } // Halt implements the Driver interface -func (d *DirectPinDriver) Halt() (err error) { return } +func (d *DirectPinDriver) Halt() error { return nil } // Off turn off pin -func (d *DirectPinDriver) Off() (err error) { +func (d *DirectPinDriver) Off() error { if writer, ok := d.Connection().(DigitalWriter); ok { return writer.DigitalWrite(d.Pin(), byte(0)) } - err = ErrDigitalWriteUnsupported - return + + return ErrDigitalWriteUnsupported } // On turn on pin -func (d *DirectPinDriver) On() (err error) { +func (d *DirectPinDriver) On() error { if writer, ok := d.Connection().(DigitalWriter); ok { return writer.DigitalWrite(d.Pin(), byte(1)) } - err = ErrDigitalWriteUnsupported - return + + return ErrDigitalWriteUnsupported } // DigitalRead returns the current digital state of the pin -func (d *DirectPinDriver) DigitalRead() (val int, err error) { +func (d *DirectPinDriver) DigitalRead() (int, error) { if reader, ok := d.Connection().(DigitalReader); ok { return reader.DigitalRead(d.Pin()) } - err = ErrDigitalReadUnsupported - return + + return 0, ErrDigitalReadUnsupported } // DigitalWrite writes to the pin. Acceptable values are 1 or 0 -func (d *DirectPinDriver) DigitalWrite(level byte) (err error) { +func (d *DirectPinDriver) DigitalWrite(level byte) error { if writer, ok := d.Connection().(DigitalWriter); ok { return writer.DigitalWrite(d.Pin(), level) } - err = ErrDigitalWriteUnsupported - return + + return ErrDigitalWriteUnsupported } // PwmWrite writes the 0-254 value to the specified pin -func (d *DirectPinDriver) PwmWrite(level byte) (err error) { +func (d *DirectPinDriver) PwmWrite(level byte) error { if writer, ok := d.Connection().(PwmWriter); ok { return writer.PwmWrite(d.Pin(), level) } - err = ErrPwmWriteUnsupported - return + + return ErrPwmWriteUnsupported } // ServoWrite writes value to the specified pin -func (d *DirectPinDriver) ServoWrite(level byte) (err error) { +func (d *DirectPinDriver) ServoWrite(level byte) error { if writer, ok := d.Connection().(ServoWriter); ok { return writer.ServoWrite(d.Pin(), level) } - err = ErrServoWriteUnsupported - return + + return ErrServoWriteUnsupported } diff --git a/drivers/gpio/direct_pin_driver_test.go b/drivers/gpio/direct_pin_driver_test.go index f9eaa96e6..1dccd9224 100644 --- a/drivers/gpio/direct_pin_driver_test.go +++ b/drivers/gpio/direct_pin_driver_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert // ok here package gpio import ( @@ -7,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -14,17 +16,16 @@ var _ gobot.Driver = (*DirectPinDriver)(nil) func initTestDirectPinDriver() *DirectPinDriver { a := newGpioTestAdaptor() - a.digitalReadFunc = func(string) (val int, err error) { - val = 1 - return + a.digitalReadFunc = func(string) (int, error) { + return 1, nil } - a.digitalWriteFunc = func(string, byte) (err error) { + a.digitalWriteFunc = func(string, byte) error { return errors.New("write error") } - a.pwmWriteFunc = func(string, byte) (err error) { + a.pwmWriteFunc = func(string, byte) error { return errors.New("write error") } - a.servoWriteFunc = func(string, byte) (err error) { + a.servoWriteFunc = func(string, byte) error { return errors.New("write error") } return NewDirectPinDriver(a, "1") diff --git a/drivers/gpio/easy_driver.go b/drivers/gpio/easy_driver.go index c7c01a8ed..4bf22cf0e 100644 --- a/drivers/gpio/easy_driver.go +++ b/drivers/gpio/easy_driver.go @@ -91,6 +91,7 @@ func (d *EasyDriver) SetDirection(direction string) error { writeVal = 1 // high is backward } + //nolint:forcetypeassert // type safe by constructor if err := d.connection.(DigitalWriter).DigitalWrite(d.dirPin, writeVal); err != nil { return err } @@ -111,6 +112,7 @@ func (d *EasyDriver) Enable() error { } // enPin is active low + //nolint:forcetypeassert // type safe by constructor if err := d.connection.(DigitalWriter).DigitalWrite(d.enPin, 0); err != nil { return err } @@ -128,6 +130,7 @@ func (d *EasyDriver) Disable() error { _ = d.stopIfRunning() // drop step errors // enPin is active low + //nolint:forcetypeassert // type safe by constructor if err := d.connection.(DigitalWriter).DigitalWrite(d.enPin, 1); err != nil { return err } @@ -148,6 +151,7 @@ func (d *EasyDriver) Wake() error { } // sleepPin is active low + //nolint:forcetypeassert // type safe by constructor if err := d.connection.(DigitalWriter).DigitalWrite(d.sleepPin, 1); err != nil { return err } @@ -171,11 +175,13 @@ func (d *EasyDriver) onePinStepping() error { defer d.valueMutex.Unlock() // a valid steps occurs for a low to high transition + //nolint:forcetypeassert // type safe by constructor if err := d.connection.(DigitalWriter).DigitalWrite(d.stepPin, 0); err != nil { return err } time.Sleep(d.getDelayPerStep()) + //nolint:forcetypeassert // type safe by constructor if err := d.connection.(DigitalWriter).DigitalWrite(d.stepPin, 1); err != nil { return err } @@ -198,6 +204,7 @@ func (d *EasyDriver) sleepWithSleepPin() error { _ = d.stopIfRunning() // drop step errors // sleepPin is active low + //nolint:forcetypeassert // type safe by constructor if err := d.connection.(DigitalWriter).DigitalWrite(d.sleepPin, 0); err != nil { return err } diff --git a/drivers/gpio/gpio_driver.go b/drivers/gpio/gpio_driver.go index 896897dcc..52d11a919 100644 --- a/drivers/gpio/gpio_driver.go +++ b/drivers/gpio/gpio_driver.go @@ -2,6 +2,7 @@ package gpio import ( "errors" + "log" "sync" "gobot.io/x/gobot/v2" @@ -47,17 +48,17 @@ const ( // PwmWriter interface represents an Adaptor which has Pwm capabilities type PwmWriter interface { - PwmWrite(pin string, val byte) (err error) + PwmWrite(pin string, val byte) error } // ServoWriter interface represents an Adaptor which has Servo capabilities type ServoWriter interface { - ServoWrite(pin string, val byte) (err error) + ServoWrite(pin string, val byte) error } // DigitalWriter interface represents an Adaptor which has DigitalWrite capabilities type DigitalWriter interface { - DigitalWrite(pin string, val byte) (err error) + DigitalWrite(pin string, val byte) error } // DigitalReader interface represents an Adaptor which has DigitalRead capabilities @@ -101,7 +102,12 @@ func (d *Driver) SetName(name string) { // Connection returns the connection of the gpio device. func (d *Driver) Connection() gobot.Connection { - return d.connection.(gobot.Connection) + if conn, ok := d.connection.(gobot.Connection); ok { + return conn + } + + log.Printf("%s has no gobot connection\n", d.name) + return nil } // Start initializes the gpio device. diff --git a/drivers/gpio/gpio_driver_test.go b/drivers/gpio/gpio_driver_test.go index 0ea6021ca..7511a3caf 100644 --- a/drivers/gpio/gpio_driver_test.go +++ b/drivers/gpio/gpio_driver_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/gpio/grove_drivers_test.go b/drivers/gpio/grove_drivers_test.go index e614432f8..1606808e2 100644 --- a/drivers/gpio/grove_drivers_test.go +++ b/drivers/gpio/grove_drivers_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert // ok here package gpio import ( @@ -9,6 +10,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -86,9 +88,8 @@ func TestDriverPublishesError(t *testing.T) { for _, driver := range drivers { sem := make(chan struct{}, 1) // send error - returnErr := func(string) (val int, err error) { - err = errors.New("read error") - return + returnErr := func(string) (int, error) { + return 0, errors.New("read error") } testAdaptor.digitalReadFunc = returnErr diff --git a/drivers/gpio/hcsr04_driver_test.go b/drivers/gpio/hcsr04_driver_test.go index da65fc901..0d49b5fe7 100644 --- a/drivers/gpio/hcsr04_driver_test.go +++ b/drivers/gpio/hcsr04_driver_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2/system" ) diff --git a/drivers/gpio/hd44780_driver.go b/drivers/gpio/hd44780_driver.go index 1f23d9101..0c24ca707 100644 --- a/drivers/gpio/hd44780_driver.go +++ b/drivers/gpio/hd44780_driver.go @@ -95,7 +95,15 @@ type HD44780Driver struct { // pinRS: register select pin // pinEN: clock enable pin // pinDataBits: databit pins -func NewHD44780Driver(a gobot.Connection, cols int, rows int, busMode HD44780BusMode, pinRS string, pinEN string, pinDataBits HD44780DataPin) *HD44780Driver { +func NewHD44780Driver( + a gobot.Connection, + cols int, + rows int, + busMode HD44780BusMode, + pinRS string, + pinEN string, + pinDataBits HD44780DataPin, +) *HD44780Driver { h := &HD44780Driver{ name: "HD44780Driver", cols: cols, @@ -157,7 +165,7 @@ func (h *HD44780Driver) Connection() gobot.Connection { // Start initializes the HD44780 LCD controller // refer to page 45/46 of Hitachi HD44780 datasheet -func (h *HD44780Driver) Start() (err error) { +func (h *HD44780Driver) Start() error { h.mutex.Lock() defer h.mutex.Unlock() @@ -252,7 +260,7 @@ func (h *HD44780Driver) Halt() error { } // Write output text to the display -func (h *HD44780Driver) Write(message string) (err error) { +func (h *HD44780Driver) Write(message string) error { h.mutex.Lock() defer h.mutex.Unlock() @@ -279,7 +287,7 @@ func (h *HD44780Driver) Write(message string) (err error) { } // Clear clear the display -func (h *HD44780Driver) Clear() (err error) { +func (h *HD44780Driver) Clear() error { h.mutex.Lock() defer h.mutex.Unlock() @@ -287,7 +295,7 @@ func (h *HD44780Driver) Clear() (err error) { } // Home return cursor to home -func (h *HD44780Driver) Home() (err error) { +func (h *HD44780Driver) Home() error { h.mutex.Lock() defer h.mutex.Unlock() @@ -300,7 +308,7 @@ func (h *HD44780Driver) Home() (err error) { } // SetCursor move the cursor to the specified position -func (h *HD44780Driver) SetCursor(col int, row int) (err error) { +func (h *HD44780Driver) SetCursor(col int, row int) error { h.mutex.Lock() defer h.mutex.Unlock() @@ -308,7 +316,7 @@ func (h *HD44780Driver) SetCursor(col int, row int) (err error) { } // Display turn the display on and off -func (h *HD44780Driver) Display(on bool) (err error) { +func (h *HD44780Driver) Display(on bool) error { h.mutex.Lock() defer h.mutex.Unlock() @@ -322,7 +330,7 @@ func (h *HD44780Driver) Display(on bool) (err error) { } // Cursor turn the cursor on and off -func (h *HD44780Driver) Cursor(on bool) (err error) { +func (h *HD44780Driver) Cursor(on bool) error { h.mutex.Lock() defer h.mutex.Unlock() @@ -336,7 +344,7 @@ func (h *HD44780Driver) Cursor(on bool) (err error) { } // Blink turn the blink on and off -func (h *HD44780Driver) Blink(on bool) (err error) { +func (h *HD44780Driver) Blink(on bool) error { h.mutex.Lock() defer h.mutex.Unlock() @@ -350,7 +358,7 @@ func (h *HD44780Driver) Blink(on bool) (err error) { } // ScrollLeft scroll text left -func (h *HD44780Driver) ScrollLeft() (err error) { +func (h *HD44780Driver) ScrollLeft() error { h.mutex.Lock() defer h.mutex.Unlock() @@ -358,7 +366,7 @@ func (h *HD44780Driver) ScrollLeft() (err error) { } // ScrollRight scroll text right -func (h *HD44780Driver) ScrollRight() (err error) { +func (h *HD44780Driver) ScrollRight() error { h.mutex.Lock() defer h.mutex.Unlock() @@ -366,7 +374,7 @@ func (h *HD44780Driver) ScrollRight() (err error) { } // LeftToRight display text from left to right -func (h *HD44780Driver) LeftToRight() (err error) { +func (h *HD44780Driver) LeftToRight() error { h.mutex.Lock() defer h.mutex.Unlock() @@ -375,7 +383,7 @@ func (h *HD44780Driver) LeftToRight() (err error) { } // RightToLeft display text from right to left -func (h *HD44780Driver) RightToLeft() (err error) { +func (h *HD44780Driver) RightToLeft() error { h.mutex.Lock() defer h.mutex.Unlock() @@ -384,7 +392,7 @@ func (h *HD44780Driver) RightToLeft() (err error) { } // SendCommand send control command -func (h *HD44780Driver) SendCommand(data int) (err error) { +func (h *HD44780Driver) SendCommand(data int) error { h.mutex.Lock() defer h.mutex.Unlock() @@ -392,7 +400,7 @@ func (h *HD44780Driver) SendCommand(data int) (err error) { } // WriteChar output a character to the display -func (h *HD44780Driver) WriteChar(data int) (err error) { +func (h *HD44780Driver) WriteChar(data int) error { h.mutex.Lock() defer h.mutex.Unlock() @@ -400,7 +408,7 @@ func (h *HD44780Driver) WriteChar(data int) (err error) { } // CreateChar create custom character -func (h *HD44780Driver) CreateChar(pos int, charMap [8]byte) (err error) { +func (h *HD44780Driver) CreateChar(pos int, charMap [8]byte) error { h.mutex.Lock() defer h.mutex.Unlock() @@ -421,7 +429,7 @@ func (h *HD44780Driver) CreateChar(pos int, charMap [8]byte) (err error) { return nil } -func (h *HD44780Driver) sendCommand(data int) (err error) { +func (h *HD44780Driver) sendCommand(data int) error { if err := h.activateWriteMode(); err != nil { return err } @@ -437,7 +445,7 @@ func (h *HD44780Driver) sendCommand(data int) (err error) { return h.writeDataPins(data) } -func (h *HD44780Driver) writeChar(data int) (err error) { +func (h *HD44780Driver) writeChar(data int) error { if err := h.activateWriteMode(); err != nil { return err } @@ -454,7 +462,7 @@ func (h *HD44780Driver) writeChar(data int) (err error) { return h.writeDataPins(data) } -func (h *HD44780Driver) clear() (err error) { +func (h *HD44780Driver) clear() error { if err := h.sendCommand(HD44780_CLEARDISPLAY); err != nil { return err } @@ -466,7 +474,7 @@ func (h *HD44780Driver) clear() (err error) { return nil } -func (h *HD44780Driver) setCursor(col int, row int) (err error) { +func (h *HD44780Driver) setCursor(col int, row int) error { if col < 0 || row < 0 || col >= h.cols || row >= h.rows { return fmt.Errorf("Invalid position value (%d, %d), range (%d, %d)", col, row, h.cols-1, h.rows-1) } @@ -474,7 +482,7 @@ func (h *HD44780Driver) setCursor(col int, row int) (err error) { return h.sendCommand(HD44780_SETDDRAMADDR | col + h.rowOffsets[row]) } -func (h *HD44780Driver) writeDataPins(data int) (err error) { +func (h *HD44780Driver) writeDataPins(data int) error { for i, pin := range h.pinDataBits { if ((data >> i) & 0x01) == 0x01 { if err := pin.On(); err != nil { @@ -490,7 +498,7 @@ func (h *HD44780Driver) writeDataPins(data int) (err error) { } // fallingEdge creates falling edge to trigger data transmission -func (h *HD44780Driver) fallingEdge() (err error) { +func (h *HD44780Driver) fallingEdge() error { if err := h.pinEN.On(); err != nil { return err } @@ -505,9 +513,9 @@ func (h *HD44780Driver) fallingEdge() (err error) { return nil } -func (h *HD44780Driver) activateWriteMode() (err error) { +func (h *HD44780Driver) activateWriteMode() error { if h.pinRW == nil { - return + return nil } return h.pinRW.Off() } diff --git a/drivers/gpio/hd44780_driver_test.go b/drivers/gpio/hd44780_driver_test.go index a69f9f775..a43778118 100644 --- a/drivers/gpio/hd44780_driver_test.go +++ b/drivers/gpio/hd44780_driver_test.go @@ -127,14 +127,14 @@ func TestHD44780DriverWriteError(t *testing.T) { var a *gpioTestAdaptor d, a = initTestHD44780Driver4BitModeWithStubbedAdaptor() - a.digitalWriteFunc = func(string, byte) (err error) { + a.digitalWriteFunc = func(string, byte) error { return errors.New("write error") } _ = d.Start() require.ErrorContains(t, d.Write("hello gobot"), "write error") d, a = initTestHD44780Driver8BitModeWithStubbedAdaptor() - a.digitalWriteFunc = func(string, byte) (err error) { + a.digitalWriteFunc = func(string, byte) error { return errors.New("write error") } _ = d.Start() diff --git a/drivers/gpio/helpers_test.go b/drivers/gpio/helpers_test.go index a12fa3983..845389dec 100644 --- a/drivers/gpio/helpers_test.go +++ b/drivers/gpio/helpers_test.go @@ -9,13 +9,13 @@ import ( type gpioTestBareAdaptor struct{} -func (t *gpioTestBareAdaptor) Connect() (err error) { return } -func (t *gpioTestBareAdaptor) Finalize() (err error) { return } -func (t *gpioTestBareAdaptor) Name() string { return "" } -func (t *gpioTestBareAdaptor) SetName(n string) {} +func (t *gpioTestBareAdaptor) Connect() error { return nil } +func (t *gpioTestBareAdaptor) Finalize() error { return nil } +func (t *gpioTestBareAdaptor) Name() string { return "" } +func (t *gpioTestBareAdaptor) SetName(n string) {} type digitalPinMock struct { - writeFunc func(val int) (err error) + writeFunc func(val int) error } type gpioTestWritten struct { @@ -31,9 +31,9 @@ type gpioTestAdaptor struct { simulateWriteError bool mtx sync.Mutex digitalReadFunc func(ping string) (val int, err error) - digitalWriteFunc func(pin string, val byte) (err error) - pwmWriteFunc func(pin string, val byte) (err error) - servoWriteFunc func(pin string, val byte) (err error) + digitalWriteFunc func(pin string, val byte) error + pwmWriteFunc func(pin string, val byte) error + servoWriteFunc func(pin string, val byte) error } func newGpioTestAdaptor() *gpioTestAdaptor { @@ -41,16 +41,16 @@ func newGpioTestAdaptor() *gpioTestAdaptor { name: "gpio_test_adaptor", pinMap: make(map[string]gobot.DigitalPinner), port: "/dev/null", - digitalWriteFunc: func(pin string, val byte) (err error) { + digitalWriteFunc: func(pin string, val byte) error { return nil }, - servoWriteFunc: func(pin string, val byte) (err error) { + servoWriteFunc: func(pin string, val byte) error { return nil }, - pwmWriteFunc: func(pin string, val byte) (err error) { + pwmWriteFunc: func(pin string, val byte) error { return nil }, - digitalReadFunc: func(pin string) (val int, err error) { + digitalReadFunc: func(pin string) (int, error) { return 1, nil }, } @@ -59,14 +59,14 @@ func newGpioTestAdaptor() *gpioTestAdaptor { } // DigitalRead capabilities (interface DigitalReader) -func (t *gpioTestAdaptor) DigitalRead(pin string) (val int, err error) { +func (t *gpioTestAdaptor) DigitalRead(pin string) (int, error) { t.mtx.Lock() defer t.mtx.Unlock() return t.digitalReadFunc(pin) } // DigitalWrite capabilities (interface DigitalWriter) -func (t *gpioTestAdaptor) DigitalWrite(pin string, val byte) (err error) { +func (t *gpioTestAdaptor) DigitalWrite(pin string, val byte) error { t.mtx.Lock() defer t.mtx.Unlock() if t.simulateWriteError { @@ -78,24 +78,24 @@ func (t *gpioTestAdaptor) DigitalWrite(pin string, val byte) (err error) { } // PwmWrite capabilities (interface PwmWriter) -func (t *gpioTestAdaptor) PwmWrite(pin string, val byte) (err error) { +func (t *gpioTestAdaptor) PwmWrite(pin string, val byte) error { t.mtx.Lock() defer t.mtx.Unlock() return t.pwmWriteFunc(pin, val) } // ServoWrite capabilities (interface ServoWriter) -func (t *gpioTestAdaptor) ServoWrite(pin string, val byte) (err error) { +func (t *gpioTestAdaptor) ServoWrite(pin string, val byte) error { t.mtx.Lock() defer t.mtx.Unlock() return t.servoWriteFunc(pin, val) } -func (t *gpioTestAdaptor) Connect() (err error) { return } -func (t *gpioTestAdaptor) Finalize() (err error) { return } -func (t *gpioTestAdaptor) Name() string { return t.name } -func (t *gpioTestAdaptor) SetName(n string) { t.name = n } -func (t *gpioTestAdaptor) Port() string { return t.port } +func (t *gpioTestAdaptor) Connect() error { return nil } +func (t *gpioTestAdaptor) Finalize() error { return nil } +func (t *gpioTestAdaptor) Name() string { return t.name } +func (t *gpioTestAdaptor) SetName(n string) { t.name = n } +func (t *gpioTestAdaptor) Port() string { return t.port } // DigitalPin (interface DigitalPinnerProvider) return a pin object func (t *gpioTestAdaptor) DigitalPin(id string) (gobot.DigitalPinner, error) { @@ -121,8 +121,8 @@ func (d *digitalPinMock) Unexport() error { } // Read (interface DigitalPinner) reads the current value of the pin -func (d *digitalPinMock) Read() (n int, err error) { - return 0, err +func (d *digitalPinMock) Read() (int, error) { + return 0, nil } // Write (interface DigitalPinner) writes to the pin @@ -132,7 +132,7 @@ func (d *digitalPinMock) Write(b int) error { func (t *gpioTestAdaptor) addDigitalPin(id string) *digitalPinMock { dpm := &digitalPinMock{ - writeFunc: func(val int) (err error) { return nil }, + writeFunc: func(val int) error { return nil }, } t.pinMap[id] = dpm return dpm diff --git a/drivers/gpio/led_driver.go b/drivers/gpio/led_driver.go index fd5f4197d..c69121424 100644 --- a/drivers/gpio/led_driver.go +++ b/drivers/gpio/led_driver.go @@ -1,6 +1,10 @@ package gpio -import "gobot.io/x/gobot/v2" +import ( + "log" + + "gobot.io/x/gobot/v2" +) // LedDriver represents a digital Led type LedDriver struct { @@ -20,7 +24,7 @@ type LedDriver struct { // "On" - See LedDriver.On // "Off" - See LedDriver.Off func NewLedDriver(a DigitalWriter, pin string) *LedDriver { - l := &LedDriver{ + d := &LedDriver{ name: gobot.DefaultName("LED"), pin: pin, connection: a, @@ -28,83 +32,86 @@ func NewLedDriver(a DigitalWriter, pin string) *LedDriver { Commander: gobot.NewCommander(), } - l.AddCommand("Brightness", func(params map[string]interface{}) interface{} { - level := byte(params["level"].(float64)) - return l.Brightness(level) + d.AddCommand("Brightness", func(params map[string]interface{}) interface{} { + level := byte(params["level"].(float64)) //nolint:forcetypeassert // ok here + return d.Brightness(level) }) - l.AddCommand("Toggle", func(params map[string]interface{}) interface{} { - return l.Toggle() + d.AddCommand("Toggle", func(params map[string]interface{}) interface{} { + return d.Toggle() }) - l.AddCommand("On", func(params map[string]interface{}) interface{} { - return l.On() + d.AddCommand("On", func(params map[string]interface{}) interface{} { + return d.On() }) - l.AddCommand("Off", func(params map[string]interface{}) interface{} { - return l.Off() + d.AddCommand("Off", func(params map[string]interface{}) interface{} { + return d.Off() }) - return l + return d } // Start implements the Driver interface -func (l *LedDriver) Start() (err error) { return } +func (d *LedDriver) Start() error { return nil } // Halt implements the Driver interface -func (l *LedDriver) Halt() (err error) { return } +func (d *LedDriver) Halt() error { return nil } // Name returns the LedDrivers name -func (l *LedDriver) Name() string { return l.name } +func (d *LedDriver) Name() string { return d.name } // SetName sets the LedDrivers name -func (l *LedDriver) SetName(n string) { l.name = n } +func (d *LedDriver) SetName(n string) { d.name = n } // Pin returns the LedDrivers name -func (l *LedDriver) Pin() string { return l.pin } +func (d *LedDriver) Pin() string { return d.pin } // Connection returns the LedDrivers Connection -func (l *LedDriver) Connection() gobot.Connection { - return l.connection.(gobot.Connection) +func (d *LedDriver) Connection() gobot.Connection { + if conn, ok := d.connection.(gobot.Connection); ok { + return conn + } + + log.Printf("%s has no gobot connection\n", d.name) + return nil } // State return true if the led is On and false if the led is Off -func (l *LedDriver) State() bool { - return l.high +func (d *LedDriver) State() bool { + return d.high } // On sets the led to a high state. -func (l *LedDriver) On() (err error) { - if err = l.connection.DigitalWrite(l.Pin(), 1); err != nil { - return +func (d *LedDriver) On() error { + if err := d.connection.DigitalWrite(d.Pin(), 1); err != nil { + return err } - l.high = true - return + d.high = true + return nil } // Off sets the led to a low state. -func (l *LedDriver) Off() (err error) { - if err = l.connection.DigitalWrite(l.Pin(), 0); err != nil { - return +func (d *LedDriver) Off() error { + if err := d.connection.DigitalWrite(d.Pin(), 0); err != nil { + return err } - l.high = false - return + d.high = false + return nil } // Toggle sets the led to the opposite of it's current state -func (l *LedDriver) Toggle() (err error) { - if l.State() { - err = l.Off() - } else { - err = l.On() +func (d *LedDriver) Toggle() error { + if d.State() { + return d.Off() } - return + return d.On() } // Brightness sets the led to the specified level of brightness -func (l *LedDriver) Brightness(level byte) (err error) { - if writer, ok := l.connection.(PwmWriter); ok { - return writer.PwmWrite(l.Pin(), level) +func (d *LedDriver) Brightness(level byte) error { + if writer, ok := d.connection.(PwmWriter); ok { + return writer.PwmWrite(d.Pin(), level) } return ErrPwmWriteUnsupported } diff --git a/drivers/gpio/led_driver_test.go b/drivers/gpio/led_driver_test.go index b5c74f629..0fef94b11 100644 --- a/drivers/gpio/led_driver_test.go +++ b/drivers/gpio/led_driver_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert // ok here package gpio import ( @@ -7,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -14,10 +16,10 @@ var _ gobot.Driver = (*LedDriver)(nil) func initTestLedDriver() *LedDriver { a := newGpioTestAdaptor() - a.digitalWriteFunc = func(string, byte) (err error) { + a.digitalWriteFunc = func(string, byte) error { return nil } - a.pwmWriteFunc = func(string, byte) (err error) { + a.pwmWriteFunc = func(string, byte) error { return nil } return NewLedDriver(a, "1") @@ -31,10 +33,10 @@ func TestLedDriver(t *testing.T) { assert.Equal(t, "1", d.Pin()) assert.NotNil(t, d.Connection()) - a.digitalWriteFunc = func(string, byte) (err error) { + a.digitalWriteFunc = func(string, byte) error { return errors.New("write error") } - a.pwmWriteFunc = func(string, byte) (err error) { + a.pwmWriteFunc = func(string, byte) error { return errors.New("pwm error") } @@ -73,9 +75,8 @@ func TestLedDriverToggle(t *testing.T) { func TestLedDriverBrightness(t *testing.T) { a := newGpioTestAdaptor() d := NewLedDriver(a, "1") - a.pwmWriteFunc = func(string, byte) (err error) { - err = errors.New("pwm error") - return + a.pwmWriteFunc = func(string, byte) error { + return errors.New("pwm error") } require.ErrorContains(t, d.Brightness(150), "pwm error") } diff --git a/drivers/gpio/max7219_driver.go b/drivers/gpio/max7219_driver.go index 216d7e26d..c4bb713c6 100644 --- a/drivers/gpio/max7219_driver.go +++ b/drivers/gpio/max7219_driver.go @@ -2,6 +2,7 @@ package gpio import ( "github.com/hashicorp/go-multierror" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/gpio/max7219_driver_test.go b/drivers/gpio/max7219_driver_test.go index 8515b6bab..e668c8952 100644 --- a/drivers/gpio/max7219_driver_test.go +++ b/drivers/gpio/max7219_driver_test.go @@ -6,15 +6,16 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) var _ gobot.Driver = (*MAX7219Driver)(nil) // --------- HELPERS -func initTestMAX7219Driver() (driver *MAX7219Driver) { - driver, _ = initTestMAX7219DriverWithStubbedAdaptor() - return +func initTestMAX7219Driver() *MAX7219Driver { + d, _ := initTestMAX7219DriverWithStubbedAdaptor() + return d } func initTestMAX7219DriverWithStubbedAdaptor() (*MAX7219Driver, *gpioTestAdaptor) { diff --git a/drivers/gpio/motor_driver.go b/drivers/gpio/motor_driver.go index f14dc9707..9f6dcfa97 100644 --- a/drivers/gpio/motor_driver.go +++ b/drivers/gpio/motor_driver.go @@ -1,6 +1,8 @@ package gpio import ( + "log" + "gobot.io/x/gobot/v2" ) @@ -33,177 +35,175 @@ func NewMotorDriver(a DigitalWriter, speedPin string) *MotorDriver { } // Name returns the MotorDrivers name -func (m *MotorDriver) Name() string { return m.name } +func (d *MotorDriver) Name() string { return d.name } // SetName sets the MotorDrivers name -func (m *MotorDriver) SetName(n string) { m.name = n } +func (d *MotorDriver) SetName(n string) { d.name = n } // Connection returns the MotorDrivers Connection -func (m *MotorDriver) Connection() gobot.Connection { return m.connection.(gobot.Connection) } +func (d *MotorDriver) Connection() gobot.Connection { + if conn, ok := d.connection.(gobot.Connection); ok { + return conn + } + + log.Printf("%s has no gobot connection\n", d.name) + return nil +} // Start implements the Driver interface -func (m *MotorDriver) Start() (err error) { return } +func (d *MotorDriver) Start() error { return nil } // Halt implements the Driver interface -func (m *MotorDriver) Halt() (err error) { return } +func (d *MotorDriver) Halt() error { return nil } // Off turns the motor off or sets the motor to a 0 speed -func (m *MotorDriver) Off() (err error) { - if m.isDigital() { - err = m.changeState(0) - } else { - err = m.Speed(0) +func (d *MotorDriver) Off() error { + if d.isDigital() { + return d.changeState(0) } - return + + return d.Speed(0) } // On turns the motor on or sets the motor to a maximum speed -func (m *MotorDriver) On() (err error) { - if m.isDigital() { - err = m.changeState(1) - } else { - if m.CurrentSpeed == 0 { - m.CurrentSpeed = 255 - } - err = m.Speed(m.CurrentSpeed) +func (d *MotorDriver) On() error { + if d.isDigital() { + return d.changeState(1) } - return + if d.CurrentSpeed == 0 { + d.CurrentSpeed = 255 + } + + return d.Speed(d.CurrentSpeed) } // Min sets the motor to the minimum speed -func (m *MotorDriver) Min() (err error) { - return m.Off() +func (d *MotorDriver) Min() error { + return d.Off() } // Max sets the motor to the maximum speed -func (m *MotorDriver) Max() (err error) { - return m.Speed(255) +func (d *MotorDriver) Max() error { + return d.Speed(255) } // IsOn returns true if the motor is on -func (m *MotorDriver) IsOn() bool { - if m.isDigital() { - return m.CurrentState == 1 +func (d *MotorDriver) IsOn() bool { + if d.isDigital() { + return d.CurrentState == 1 } - return m.CurrentSpeed > 0 + return d.CurrentSpeed > 0 } // IsOff returns true if the motor is off -func (m *MotorDriver) IsOff() bool { - return !m.IsOn() +func (d *MotorDriver) IsOff() bool { + return !d.IsOn() } // Toggle sets the motor to the opposite of it's current state -func (m *MotorDriver) Toggle() (err error) { - if m.IsOn() { - err = m.Off() - } else { - err = m.On() +func (d *MotorDriver) Toggle() error { + if d.IsOn() { + return d.Off() } - return + + return d.On() } // Speed sets the speed of the motor -func (m *MotorDriver) Speed(value byte) (err error) { - if writer, ok := m.connection.(PwmWriter); ok { - m.CurrentMode = "analog" - m.CurrentSpeed = value - return writer.PwmWrite(m.SpeedPin, value) +func (d *MotorDriver) Speed(value byte) error { + if writer, ok := d.connection.(PwmWriter); ok { + d.CurrentMode = "analog" + d.CurrentSpeed = value + return writer.PwmWrite(d.SpeedPin, value) } return ErrPwmWriteUnsupported } // Forward sets the forward pin to the specified speed -func (m *MotorDriver) Forward(speed byte) (err error) { - err = m.Direction("forward") - if err != nil { - return +func (d *MotorDriver) Forward(speed byte) error { + if err := d.Direction("forward"); err != nil { + return err } - err = m.Speed(speed) - if err != nil { - return + if err := d.Speed(speed); err != nil { + return err } - return + + return nil } // Backward sets the backward pin to the specified speed -func (m *MotorDriver) Backward(speed byte) (err error) { - err = m.Direction("backward") - if err != nil { - return +func (d *MotorDriver) Backward(speed byte) error { + if err := d.Direction("backward"); err != nil { + return err } - err = m.Speed(speed) - if err != nil { - return + if err := d.Speed(speed); err != nil { + return err } - return + + return nil } // Direction sets the direction pin to the specified speed -func (m *MotorDriver) Direction(direction string) (err error) { - m.CurrentDirection = direction - if m.DirectionPin != "" { +func (d *MotorDriver) Direction(direction string) error { + d.CurrentDirection = direction + if d.DirectionPin != "" { var level byte if direction == "forward" { level = 1 } else { level = 0 } - err = m.connection.DigitalWrite(m.DirectionPin, level) - } else { - var forwardLevel, backwardLevel byte - switch direction { - case "forward": - forwardLevel = 1 - backwardLevel = 0 - case "backward": - forwardLevel = 0 - backwardLevel = 1 - case "none": - forwardLevel = 0 - backwardLevel = 0 - } - err = m.connection.DigitalWrite(m.ForwardPin, forwardLevel) - if err != nil { - return - } - err = m.connection.DigitalWrite(m.BackwardPin, backwardLevel) - if err != nil { - return - } + return d.connection.DigitalWrite(d.DirectionPin, level) + } + + var forwardLevel, backwardLevel byte + switch direction { + case "forward": + forwardLevel = 1 + backwardLevel = 0 + case "backward": + forwardLevel = 0 + backwardLevel = 1 + case "none": + forwardLevel = 0 + backwardLevel = 0 } - return + + if err := d.connection.DigitalWrite(d.ForwardPin, forwardLevel); err != nil { + return err + } + + return d.connection.DigitalWrite(d.BackwardPin, backwardLevel) } -func (m *MotorDriver) isDigital() bool { - return m.CurrentMode == "digital" +func (d *MotorDriver) isDigital() bool { + return d.CurrentMode == "digital" } -func (m *MotorDriver) changeState(state byte) (err error) { - m.CurrentState = state +func (d *MotorDriver) changeState(state byte) error { + d.CurrentState = state if state == 1 { - m.CurrentSpeed = 255 + d.CurrentSpeed = 255 } else { - m.CurrentSpeed = 0 - } - if m.ForwardPin != "" { - if state == 1 { - err = m.Direction(m.CurrentDirection) - if err != nil { - return - } - if m.SpeedPin != "" { - err = m.Speed(m.CurrentSpeed) - if err != nil { - return - } - } - } else { - err = m.Direction("none") + d.CurrentSpeed = 0 + } + + if d.ForwardPin == "" { + return d.connection.DigitalWrite(d.SpeedPin, state) + } + + if state != 1 { + return d.Direction("none") + } + + if err := d.Direction(d.CurrentDirection); err != nil { + return err + } + if d.SpeedPin != "" { + if err := d.Speed(d.CurrentSpeed); err != nil { + return err } - } else { - err = m.connection.DigitalWrite(m.SpeedPin, state) } - return + return nil } diff --git a/drivers/gpio/motor_driver_test.go b/drivers/gpio/motor_driver_test.go index 5864b791c..f8610fb32 100644 --- a/drivers/gpio/motor_driver_test.go +++ b/drivers/gpio/motor_driver_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/gpio/pir_motion_driver.go b/drivers/gpio/pir_motion_driver.go index aa32b50e5..e75ef2b0d 100644 --- a/drivers/gpio/pir_motion_driver.go +++ b/drivers/gpio/pir_motion_driver.go @@ -23,7 +23,8 @@ type PIRMotionDriver struct { // // time.Duration: Interval at which the PIRMotionDriver is polled for new information func NewPIRMotionDriver(a DigitalReader, pin string, v ...time.Duration) *PIRMotionDriver { - b := &PIRMotionDriver{ + //nolint:forcetypeassert // no error return value, so there is no better way + d := &PIRMotionDriver{ Driver: NewDriver(a.(gobot.Connection), "PIRMotion"), Eventer: gobot.NewEventer(), pin: pin, @@ -31,30 +32,30 @@ func NewPIRMotionDriver(a DigitalReader, pin string, v ...time.Duration) *PIRMot interval: 10 * time.Millisecond, halt: make(chan bool), } - b.afterStart = b.initialize - b.beforeHalt = b.shutdown + d.afterStart = d.initialize + d.beforeHalt = d.shutdown if len(v) > 0 { - b.interval = v[0] + d.interval = v[0] } - b.AddEvent(MotionDetected) - b.AddEvent(MotionStopped) - b.AddEvent(Error) + d.AddEvent(MotionDetected) + d.AddEvent(MotionStopped) + d.AddEvent(Error) - return b + return d } // Pin returns the PIRMotionDriver pin -func (p *PIRMotionDriver) Pin() string { return p.pin } +func (d *PIRMotionDriver) Pin() string { return d.pin } // Active gets the current state -func (p *PIRMotionDriver) Active() bool { +func (d *PIRMotionDriver) Active() bool { // ensure that read and write can not interfere - p.mutex.Lock() - defer p.mutex.Unlock() + d.mutex.Lock() + defer d.mutex.Unlock() - return p.active + return d.active } // initialize the PIRMotionDriver and polls the state of the sensor at the given interval. @@ -69,17 +70,17 @@ func (p *PIRMotionDriver) Active() bool { // just as long as motion is still being detected. // It will only send the MotionStopped event once, however, until // motion starts being detected again -func (p *PIRMotionDriver) initialize() error { +func (d *PIRMotionDriver) initialize() error { go func() { for { - newValue, err := p.connection.(DigitalReader).DigitalRead(p.Pin()) + newValue, err := d.connection.(DigitalReader).DigitalRead(d.Pin()) if err != nil { - p.Publish(Error, err) + d.Publish(Error, err) } - p.update(newValue) + d.update(newValue) select { - case <-time.After(p.interval): - case <-p.halt: + case <-time.After(d.interval): + case <-d.halt: return } } @@ -88,26 +89,26 @@ func (p *PIRMotionDriver) initialize() error { } // shutdown stops polling -func (p *PIRMotionDriver) shutdown() error { - p.halt <- true +func (d *PIRMotionDriver) shutdown() error { + d.halt <- true return nil } -func (p *PIRMotionDriver) update(newValue int) { +func (d *PIRMotionDriver) update(newValue int) { // ensure that read and write can not interfere - p.mutex.Lock() - defer p.mutex.Unlock() + d.mutex.Lock() + defer d.mutex.Unlock() switch newValue { case 1: - if !p.active { - p.active = true - p.Publish(MotionDetected, newValue) + if !d.active { + d.active = true + d.Publish(MotionDetected, newValue) } case 0: - if p.active { - p.active = false - p.Publish(MotionStopped, newValue) + if d.active { + d.active = false + d.Publish(MotionStopped, newValue) } } } diff --git a/drivers/gpio/pir_motion_driver_test.go b/drivers/gpio/pir_motion_driver_test.go index 709f07b61..04e4c3f79 100644 --- a/drivers/gpio/pir_motion_driver_test.go +++ b/drivers/gpio/pir_motion_driver_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/gpio/relay_driver.go b/drivers/gpio/relay_driver.go index 5a4861ef1..8c8d9e935 100644 --- a/drivers/gpio/relay_driver.go +++ b/drivers/gpio/relay_driver.go @@ -1,6 +1,10 @@ package gpio -import "gobot.io/x/gobot/v2" +import ( + "log" + + "gobot.io/x/gobot/v2" +) // RelayDriver represents a digital relay type RelayDriver struct { @@ -20,7 +24,7 @@ type RelayDriver struct { // "On" - See RelayDriver.On // "Off" - See RelayDriver.Off func NewRelayDriver(a DigitalWriter, pin string) *RelayDriver { - l := &RelayDriver{ + d := &RelayDriver{ name: gobot.DefaultName("Relay"), pin: pin, connection: a, @@ -29,93 +33,97 @@ func NewRelayDriver(a DigitalWriter, pin string) *RelayDriver { Commander: gobot.NewCommander(), } - l.AddCommand("Toggle", func(params map[string]interface{}) interface{} { - return l.Toggle() + d.AddCommand("Toggle", func(params map[string]interface{}) interface{} { + return d.Toggle() }) - l.AddCommand("On", func(params map[string]interface{}) interface{} { - return l.On() + d.AddCommand("On", func(params map[string]interface{}) interface{} { + return d.On() }) - l.AddCommand("Off", func(params map[string]interface{}) interface{} { - return l.Off() + d.AddCommand("Off", func(params map[string]interface{}) interface{} { + return d.Off() }) - return l + return d } // Start implements the Driver interface -func (l *RelayDriver) Start() (err error) { return } +func (d *RelayDriver) Start() error { return nil } // Halt implements the Driver interface -func (l *RelayDriver) Halt() (err error) { return } +func (d *RelayDriver) Halt() error { return nil } // Name returns the RelayDrivers name -func (l *RelayDriver) Name() string { return l.name } +func (d *RelayDriver) Name() string { return d.name } // SetName sets the RelayDrivers name -func (l *RelayDriver) SetName(n string) { l.name = n } +func (d *RelayDriver) SetName(n string) { d.name = n } // Pin returns the RelayDrivers name -func (l *RelayDriver) Pin() string { return l.pin } +func (d *RelayDriver) Pin() string { return d.pin } // Connection returns the RelayDrivers Connection -func (l *RelayDriver) Connection() gobot.Connection { - return l.connection.(gobot.Connection) +func (d *RelayDriver) Connection() gobot.Connection { + if conn, ok := d.connection.(gobot.Connection); ok { + return conn + } + + log.Printf("%s has no gobot connection\n", d.name) + return nil } // State return true if the relay is On and false if the relay is Off -func (l *RelayDriver) State() bool { - if l.Inverted { - return !l.high +func (d *RelayDriver) State() bool { + if d.Inverted { + return !d.high } - return l.high + return d.high } // On sets the relay to a high state. -func (l *RelayDriver) On() (err error) { +func (d *RelayDriver) On() error { newValue := byte(1) - if l.Inverted { + if d.Inverted { newValue = 0 } - if err = l.connection.DigitalWrite(l.Pin(), newValue); err != nil { - return + if err := d.connection.DigitalWrite(d.Pin(), newValue); err != nil { + return err } - if l.Inverted { - l.high = false + if d.Inverted { + d.high = false } else { - l.high = true + d.high = true } - return + return nil } // Off sets the relay to a low state. -func (l *RelayDriver) Off() (err error) { +func (d *RelayDriver) Off() error { newValue := byte(0) - if l.Inverted { + if d.Inverted { newValue = 1 } - if err = l.connection.DigitalWrite(l.Pin(), newValue); err != nil { - return + if err := d.connection.DigitalWrite(d.Pin(), newValue); err != nil { + return err } - if l.Inverted { - l.high = true + if d.Inverted { + d.high = true } else { - l.high = false + d.high = false } - return + return nil } // Toggle sets the relay to the opposite of it's current state -func (l *RelayDriver) Toggle() (err error) { - if l.State() { - err = l.Off() - } else { - err = l.On() +func (d *RelayDriver) Toggle() error { + if d.State() { + return d.Off() } - return + + return d.On() } diff --git a/drivers/gpio/relay_driver_test.go b/drivers/gpio/relay_driver_test.go index 320034403..6cf319c60 100644 --- a/drivers/gpio/relay_driver_test.go +++ b/drivers/gpio/relay_driver_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -16,10 +17,10 @@ func (l *RelayDriver) High() bool { return l.high } func initTestRelayDriver() (*RelayDriver, *gpioTestAdaptor) { a := newGpioTestAdaptor() - a.digitalWriteFunc = func(string, byte) (err error) { + a.digitalWriteFunc = func(string, byte) error { return nil } - a.pwmWriteFunc = func(string, byte) (err error) { + a.pwmWriteFunc = func(string, byte) error { return nil } return NewRelayDriver(a, "1"), a diff --git a/drivers/gpio/rgb_led_driver.go b/drivers/gpio/rgb_led_driver.go index 22116a155..c67b90080 100644 --- a/drivers/gpio/rgb_led_driver.go +++ b/drivers/gpio/rgb_led_driver.go @@ -1,6 +1,10 @@ package gpio -import "gobot.io/x/gobot/v2" +import ( + "log" + + "gobot.io/x/gobot/v2" +) // RgbLedDriver represents a digital RGB Led type RgbLedDriver struct { @@ -26,7 +30,7 @@ type RgbLedDriver struct { // "On" - See RgbLedDriver.On // "Off" - See RgbLedDriver.Off func NewRgbLedDriver(a DigitalWriter, redPin string, greenPin string, bluePin string) *RgbLedDriver { - l := &RgbLedDriver{ + d := &RgbLedDriver{ name: gobot.DefaultName("RGBLED"), pinRed: redPin, pinGreen: greenPin, @@ -36,123 +40,128 @@ func NewRgbLedDriver(a DigitalWriter, redPin string, greenPin string, bluePin st Commander: gobot.NewCommander(), } - l.AddCommand("SetRGB", func(params map[string]interface{}) interface{} { + //nolint:forcetypeassert // ok here + d.AddCommand("SetRGB", func(params map[string]interface{}) interface{} { r := byte(params["r"].(int)) g := byte(params["g"].(int)) b := byte(params["b"].(int)) - return l.SetRGB(r, g, b) + return d.SetRGB(r, g, b) }) - l.AddCommand("Toggle", func(params map[string]interface{}) interface{} { - return l.Toggle() + d.AddCommand("Toggle", func(params map[string]interface{}) interface{} { + return d.Toggle() }) - l.AddCommand("On", func(params map[string]interface{}) interface{} { - return l.On() + d.AddCommand("On", func(params map[string]interface{}) interface{} { + return d.On() }) - l.AddCommand("Off", func(params map[string]interface{}) interface{} { - return l.Off() + d.AddCommand("Off", func(params map[string]interface{}) interface{} { + return d.Off() }) - return l + return d } // Start implements the Driver interface -func (l *RgbLedDriver) Start() (err error) { return } +func (d *RgbLedDriver) Start() error { return nil } // Halt implements the Driver interface -func (l *RgbLedDriver) Halt() (err error) { return } +func (d *RgbLedDriver) Halt() error { return nil } // Name returns the RGBLEDDrivers name -func (l *RgbLedDriver) Name() string { return l.name } +func (d *RgbLedDriver) Name() string { return d.name } // SetName sets the RGBLEDDrivers name -func (l *RgbLedDriver) SetName(n string) { l.name = n } +func (d *RgbLedDriver) SetName(n string) { d.name = n } // Pin returns the RgbLedDrivers pins -func (l *RgbLedDriver) Pin() string { - return "r=" + l.pinRed + ", g=" + l.pinGreen + ", b=" + l.pinBlue +func (d *RgbLedDriver) Pin() string { + return "r=" + d.pinRed + ", g=" + d.pinGreen + ", b=" + d.pinBlue } // RedPin returns the RgbLedDrivers redPin -func (l *RgbLedDriver) RedPin() string { return l.pinRed } +func (d *RgbLedDriver) RedPin() string { return d.pinRed } // GreenPin returns the RgbLedDrivers redPin -func (l *RgbLedDriver) GreenPin() string { return l.pinGreen } +func (d *RgbLedDriver) GreenPin() string { return d.pinGreen } // BluePin returns the RgbLedDrivers bluePin -func (l *RgbLedDriver) BluePin() string { return l.pinBlue } +func (d *RgbLedDriver) BluePin() string { return d.pinBlue } // Connection returns the RgbLedDriver Connection -func (l *RgbLedDriver) Connection() gobot.Connection { - return l.connection.(gobot.Connection) +func (d *RgbLedDriver) Connection() gobot.Connection { + if conn, ok := d.connection.(gobot.Connection); ok { + return conn + } + + log.Printf("%s has no gobot connection\n", d.name) + return nil } // State return true if the led is On and false if the led is Off -func (l *RgbLedDriver) State() bool { - return l.high +func (d *RgbLedDriver) State() bool { + return d.high } // On sets the led's pins to their various states -func (l *RgbLedDriver) On() (err error) { - if err = l.SetLevel(l.pinRed, l.redColor); err != nil { - return +func (d *RgbLedDriver) On() error { + if err := d.SetLevel(d.pinRed, d.redColor); err != nil { + return err } - if err = l.SetLevel(l.pinGreen, l.greenColor); err != nil { - return + if err := d.SetLevel(d.pinGreen, d.greenColor); err != nil { + return err } - if err = l.SetLevel(l.pinBlue, l.blueColor); err != nil { - return + if err := d.SetLevel(d.pinBlue, d.blueColor); err != nil { + return err } - l.high = true - return + d.high = true + return nil } // Off sets the led to black. -func (l *RgbLedDriver) Off() (err error) { - if err = l.SetLevel(l.pinRed, 0); err != nil { - return +func (d *RgbLedDriver) Off() error { + if err := d.SetLevel(d.pinRed, 0); err != nil { + return err } - if err = l.SetLevel(l.pinGreen, 0); err != nil { - return + if err := d.SetLevel(d.pinGreen, 0); err != nil { + return err } - if err = l.SetLevel(l.pinBlue, 0); err != nil { - return + if err := d.SetLevel(d.pinBlue, 0); err != nil { + return err } - l.high = false - return + d.high = false + return nil } // Toggle sets the led to the opposite of it's current state -func (l *RgbLedDriver) Toggle() (err error) { - if l.State() { - err = l.Off() - } else { - err = l.On() +func (d *RgbLedDriver) Toggle() error { + if d.State() { + return d.Off() } - return + + return d.On() } // SetLevel sets the led to the specified color level -func (l *RgbLedDriver) SetLevel(pin string, level byte) (err error) { - if writer, ok := l.connection.(PwmWriter); ok { +func (d *RgbLedDriver) SetLevel(pin string, level byte) error { + if writer, ok := d.connection.(PwmWriter); ok { return writer.PwmWrite(pin, level) } return ErrPwmWriteUnsupported } // SetRGB sets the Red Green Blue value of the LED. -func (l *RgbLedDriver) SetRGB(r, g, b byte) error { - l.redColor = r - l.greenColor = g - l.blueColor = b +func (d *RgbLedDriver) SetRGB(r, g, b byte) error { + d.redColor = r + d.greenColor = g + d.blueColor = b - return l.On() + return d.On() } diff --git a/drivers/gpio/rgb_led_driver_test.go b/drivers/gpio/rgb_led_driver_test.go index 46121ca33..b4b057986 100644 --- a/drivers/gpio/rgb_led_driver_test.go +++ b/drivers/gpio/rgb_led_driver_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert // ok here package gpio import ( @@ -7,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -14,10 +16,10 @@ var _ gobot.Driver = (*RgbLedDriver)(nil) func initTestRgbLedDriver() *RgbLedDriver { a := newGpioTestAdaptor() - a.digitalWriteFunc = func(string, byte) (err error) { + a.digitalWriteFunc = func(string, byte) error { return nil } - a.pwmWriteFunc = func(string, byte) (err error) { + a.pwmWriteFunc = func(string, byte) error { return nil } return NewRgbLedDriver(a, "1", "2", "3") @@ -35,10 +37,10 @@ func TestRgbLedDriver(t *testing.T) { assert.Equal(t, "3", d.BluePin()) assert.NotNil(t, d.Connection()) - a.digitalWriteFunc = func(string, byte) (err error) { + a.digitalWriteFunc = func(string, byte) error { return errors.New("write error") } - a.pwmWriteFunc = func(string, byte) (err error) { + a.pwmWriteFunc = func(string, byte) error { return errors.New("pwm error") } @@ -80,9 +82,8 @@ func TestRgbLedDriverSetLevel(t *testing.T) { require.NoError(t, d.SetLevel("1", 150)) d = NewRgbLedDriver(a, "1", "2", "3") - a.pwmWriteFunc = func(string, byte) (err error) { - err = errors.New("pwm error") - return + a.pwmWriteFunc = func(string, byte) error { + return errors.New("pwm error") } require.ErrorContains(t, d.SetLevel("1", 150), "pwm error") } diff --git a/drivers/gpio/servo_driver.go b/drivers/gpio/servo_driver.go index 461b842f7..57a4ffea8 100644 --- a/drivers/gpio/servo_driver.go +++ b/drivers/gpio/servo_driver.go @@ -1,6 +1,10 @@ package gpio -import "gobot.io/x/gobot/v2" +import ( + "log" + + "gobot.io/x/gobot/v2" +) // ServoDriver Represents a Servo type ServoDriver struct { @@ -20,7 +24,7 @@ type ServoDriver struct { // "Center" - See ServoDriver.Center // "Max" - See ServoDriver.Max func NewServoDriver(a ServoWriter, pin string) *ServoDriver { - s := &ServoDriver{ + d := &ServoDriver{ name: gobot.DefaultName("Servo"), connection: a, pin: pin, @@ -28,61 +32,68 @@ func NewServoDriver(a ServoWriter, pin string) *ServoDriver { CurrentAngle: 0, } - s.AddCommand("Move", func(params map[string]interface{}) interface{} { - angle := byte(params["angle"].(float64)) - return s.Move(angle) + d.AddCommand("Move", func(params map[string]interface{}) interface{} { + angle := byte(params["angle"].(float64)) //nolint:forcetypeassert // ok here + return d.Move(angle) }) - s.AddCommand("Min", func(params map[string]interface{}) interface{} { - return s.Min() + d.AddCommand("Min", func(params map[string]interface{}) interface{} { + return d.Min() }) - s.AddCommand("Center", func(params map[string]interface{}) interface{} { - return s.Center() + d.AddCommand("Center", func(params map[string]interface{}) interface{} { + return d.Center() }) - s.AddCommand("Max", func(params map[string]interface{}) interface{} { - return s.Max() + d.AddCommand("Max", func(params map[string]interface{}) interface{} { + return d.Max() }) - return s + return d } // Name returns the ServoDrivers name -func (s *ServoDriver) Name() string { return s.name } +func (d *ServoDriver) Name() string { return d.name } // SetName sets the ServoDrivers name -func (s *ServoDriver) SetName(n string) { s.name = n } +func (d *ServoDriver) SetName(n string) { d.name = n } // Pin returns the ServoDrivers pin -func (s *ServoDriver) Pin() string { return s.pin } +func (d *ServoDriver) Pin() string { return d.pin } // Connection returns the ServoDrivers connection -func (s *ServoDriver) Connection() gobot.Connection { return s.connection.(gobot.Connection) } +func (d *ServoDriver) Connection() gobot.Connection { + if conn, ok := d.connection.(gobot.Connection); ok { + return conn + } + + log.Printf("%s has no gobot connection\n", d.name) + return nil +} // Start implements the Driver interface -func (s *ServoDriver) Start() (err error) { return } +func (d *ServoDriver) Start() error { return nil } // Halt implements the Driver interface -func (s *ServoDriver) Halt() (err error) { return } +func (d *ServoDriver) Halt() error { return nil } // Move sets the servo to the specified angle. Acceptable angles are 0-180 -func (s *ServoDriver) Move(angle uint8) (err error) { +func (d *ServoDriver) Move(angle uint8) error { if angle > 180 { return ErrServoOutOfRange } - s.CurrentAngle = angle - return s.connection.ServoWrite(s.Pin(), angle) + d.CurrentAngle = angle + return d.connection.ServoWrite(d.Pin(), angle) } // Min sets the servo to it's minimum position -func (s *ServoDriver) Min() (err error) { - return s.Move(0) +func (d *ServoDriver) Min() error { + return d.Move(0) } // Center sets the servo to it's center position -func (s *ServoDriver) Center() (err error) { - return s.Move(90) +func (d *ServoDriver) Center() error { + return d.Move(90) } // Max sets the servo to its maximum position -func (s *ServoDriver) Max() (err error) { - return s.Move(180) +func (d *ServoDriver) Max() error { + return d.Move(180) } diff --git a/drivers/gpio/servo_driver_test.go b/drivers/gpio/servo_driver_test.go index a0db6d242..ee05e932f 100644 --- a/drivers/gpio/servo_driver_test.go +++ b/drivers/gpio/servo_driver_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert // ok here package gpio import ( @@ -7,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -25,7 +27,7 @@ func TestServoDriver(t *testing.T) { assert.Equal(t, "1", d.Pin()) assert.NotNil(t, d.Connection()) - a.servoWriteFunc = func(string, byte) (err error) { + a.servoWriteFunc = func(string, byte) error { return errors.New("pwm error") } diff --git a/drivers/gpio/stepper_driver.go b/drivers/gpio/stepper_driver.go index 626302f8e..f3ae3bdc6 100644 --- a/drivers/gpio/stepper_driver.go +++ b/drivers/gpio/stepper_driver.go @@ -89,6 +89,7 @@ func NewStepperDriver(a DigitalWriter, pins [4]string, phase phase, stepsPerRev if stepsPerRev <= 0 { panic("steps per revolution needs to be greater than zero") } + //nolint:forcetypeassert // no error return value, so there is no better way d := &StepperDriver{ Driver: NewDriver(a.(gobot.Connection), "Stepper"), pins: pins, @@ -150,7 +151,7 @@ func (d *StepperDriver) Move(stepsToMove int) error { return err } -// MoveDeg moves the motor given number of degrees at current speed. Negative values cause to move in backward direction. +// MoveDeg moves the motor given number of degrees at current speed. Negative values cause to move backward. func (d *StepperDriver) MoveDeg(degs int) error { d.mutex.Lock() defer d.mutex.Unlock() @@ -421,8 +422,8 @@ func (d *StepperDriver) getDelayPerStep() time.Duration { return time.Duration(60*1000*1000/(d.stepsPerRev*float32(d.speedRpm))) * time.Microsecond } -// phasedStepping moves the motor one step with the configured speed and direction. The speed can be adjusted by SetSpeed() -// and the direction can be changed by SetDirection() asynchronously. +// phasedStepping moves the motor one step with the configured speed and direction. The speed can be adjusted +// by SetSpeed() and the direction can be changed by SetDirection() asynchronously. func (d *StepperDriver) phasedStepping() error { // ensure that read and write of variables (direction, stepNum) can not interfere d.valueMutex.Lock() @@ -445,6 +446,7 @@ func (d *StepperDriver) phasedStepping() error { r := int(math.Abs(float64(d.stepNum))) % len(d.phase) for i, v := range d.phase[r] { + //nolint:forcetypeassert // type safe by constructor if err := d.connection.(DigitalWriter).DigitalWrite(d.pins[i], v); err != nil { d.stepNum = oldStepNum return err @@ -459,6 +461,7 @@ func (d *StepperDriver) phasedStepping() error { func (d *StepperDriver) sleepOuputs() error { for _, pin := range d.pins { + //nolint:forcetypeassert // type safe by constructor if err := d.connection.(DigitalWriter).DigitalWrite(pin, 0); err != nil { return err } diff --git a/drivers/gpio/tm1638_driver.go b/drivers/gpio/tm1638_driver.go index 588671433..8b89ccff7 100644 --- a/drivers/gpio/tm1638_driver.go +++ b/drivers/gpio/tm1638_driver.go @@ -25,7 +25,7 @@ const ( TM1638FixedAddr = 0x04 ) -// TM1638Driver is the gobot driver for modules based on the TM1638, which has 8 7-segment displays, 8 LEDs and 8 buttons +// TM1638Driver is the driver for modules based on the TM1638, which has 8 7-segment displays, 8 LEDs and 8 buttons. // Buttons are not supported // // Datasheet EN: https://retrocip.cz/files/tm1638.pdf diff --git a/drivers/gpio/tm1638_driver_test.go b/drivers/gpio/tm1638_driver_test.go index dc916d9ba..ba60fa8d8 100644 --- a/drivers/gpio/tm1638_driver_test.go +++ b/drivers/gpio/tm1638_driver_test.go @@ -6,15 +6,16 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) var _ gobot.Driver = (*TM1638Driver)(nil) // --------- HELPERS -func initTestTM1638Driver() (driver *TM1638Driver) { - driver, _ = initTestTM1638DriverWithStubbedAdaptor() - return +func initTestTM1638Driver() *TM1638Driver { + d, _ := initTestTM1638DriverWithStubbedAdaptor() + return d } func initTestTM1638DriverWithStubbedAdaptor() (*TM1638Driver, *gpioTestAdaptor) { diff --git a/drivers/i2c/adafruit1109_driver.go b/drivers/i2c/adafruit1109_driver.go index feae2530f..c8eabeca9 100644 --- a/drivers/i2c/adafruit1109_driver.go +++ b/drivers/i2c/adafruit1109_driver.go @@ -45,7 +45,7 @@ type Adafruit1109Driver struct { // NewAdafruit1109Driver creates is a new driver for the 2x16 LCD display with RGB backlit and 5 keys. // -// Because HD44780 and MCP23017 are already implemented in gobot, we creates a wrapper for using existing implementation. +// Because HD44780 and MCP23017 are already implemented in gobot, this is a wrapper for using existing implementation. // So, for the documentation of the parameters, have a look at this drivers. // // Tests are done with a Tinkerboard. diff --git a/drivers/i2c/adafruit1109_driver_test.go b/drivers/i2c/adafruit1109_driver_test.go index 838f57592..6b1a61b62 100644 --- a/drivers/i2c/adafruit1109_driver_test.go +++ b/drivers/i2c/adafruit1109_driver_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/i2c/adafruit2327_driver_test.go b/drivers/i2c/adafruit2327_driver_test.go index b070c3f4b..e8558ab57 100644 --- a/drivers/i2c/adafruit2327_driver_test.go +++ b/drivers/i2c/adafruit2327_driver_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/i2c/adafruit2348_driver.go b/drivers/i2c/adafruit2348_driver.go index f6014b2b6..2fdf86a47 100644 --- a/drivers/i2c/adafruit2348_driver.go +++ b/drivers/i2c/adafruit2348_driver.go @@ -260,16 +260,17 @@ func (a *Adafruit2348Driver) oneStep(motor int, dir Adafruit2348Direction, style pwmA = 0 pwmB = 0 currStep := a.stepperMotors[motor].currentStep - if currStep >= 0 && currStep < adafruit2348StepperMicrosteps { + switch { + case currStep >= 0 && currStep < adafruit2348StepperMicrosteps: pwmA = a.stepperMicrostepCurve[adafruit2348StepperMicrosteps-currStep] pwmB = a.stepperMicrostepCurve[currStep] - } else if currStep >= adafruit2348StepperMicrosteps && currStep < adafruit2348StepperMicrosteps*2 { + case currStep >= adafruit2348StepperMicrosteps && currStep < adafruit2348StepperMicrosteps*2: pwmA = a.stepperMicrostepCurve[currStep-adafruit2348StepperMicrosteps] pwmB = a.stepperMicrostepCurve[adafruit2348StepperMicrosteps*2-currStep] - } else if currStep >= adafruit2348StepperMicrosteps*2 && currStep < adafruit2348StepperMicrosteps*3 { + case currStep >= adafruit2348StepperMicrosteps*2 && currStep < adafruit2348StepperMicrosteps*3: pwmA = a.stepperMicrostepCurve[adafruit2348StepperMicrosteps*3-currStep] pwmB = a.stepperMicrostepCurve[currStep-adafruit2348StepperMicrosteps*2] - } else if currStep >= adafruit2348StepperMicrosteps*3 && currStep < adafruit2348StepperMicrosteps*4 { + case currStep >= adafruit2348StepperMicrosteps*3 && currStep < adafruit2348StepperMicrosteps*4: pwmA = a.stepperMicrostepCurve[currStep-adafruit2348StepperMicrosteps*3] pwmB = a.stepperMicrostepCurve[adafruit2348StepperMicrosteps*4-currStep] } diff --git a/drivers/i2c/adafruit2348_driver_test.go b/drivers/i2c/adafruit2348_driver_test.go index a791f646f..104f1df21 100644 --- a/drivers/i2c/adafruit2348_driver_test.go +++ b/drivers/i2c/adafruit2348_driver_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/i2c/ads1x15_driver.go b/drivers/i2c/ads1x15_driver.go index 487dcb16e..1e3fbb30a 100644 --- a/drivers/i2c/ads1x15_driver.go +++ b/drivers/i2c/ads1x15_driver.go @@ -113,11 +113,12 @@ func newADS1x15Driver(c Connector, name string, drs map[int]uint16, ddr int, opt } d.AddCommand("ReadDifferenceWithDefaults", func(params map[string]interface{}) interface{} { - channel := params["channel"].(int) + channel := params["channel"].(int) //nolint:forcetypeassert // ok here val, err := d.ReadDifferenceWithDefaults(channel) return map[string]interface{}{"val": val, "err": err} }) + //nolint:forcetypeassert // ok here d.AddCommand("ReadDifference", func(params map[string]interface{}) interface{} { channel := params["channel"].(int) gain := params["gain"].(int) @@ -127,11 +128,12 @@ func newADS1x15Driver(c Connector, name string, drs map[int]uint16, ddr int, opt }) d.AddCommand("ReadWithDefaults", func(params map[string]interface{}) interface{} { - channel := params["channel"].(int) + channel := params["channel"].(int) //nolint:forcetypeassert // ok here val, err := d.ReadWithDefaults(channel) return map[string]interface{}{"val": val, "err": err} }) + //nolint:forcetypeassert // ok here d.AddCommand("Read", func(params map[string]interface{}) interface{} { channel := params["channel"].(int) gain := params["gain"].(int) @@ -141,7 +143,7 @@ func newADS1x15Driver(c Connector, name string, drs map[int]uint16, ddr int, opt }) d.AddCommand("AnalogRead", func(params map[string]interface{}) interface{} { - pin := params["pin"].(string) + pin := params["pin"].(string) //nolint:forcetypeassert // ok here val, err := d.AnalogRead(pin) return map[string]interface{}{"val": val, "err": err} }) @@ -281,12 +283,12 @@ func WithADS1x15WaitSingleCycle() func(Config) { // * 1: Channel 0 - channel 3 // * 2: Channel 1 - channel 3 // * 3: Channel 2 - channel 3 -func (d *ADS1x15Driver) ReadDifferenceWithDefaults(diff int) (value float64, err error) { +func (d *ADS1x15Driver) ReadDifferenceWithDefaults(diff int) (float64, error) { d.mutex.Lock() defer d.mutex.Unlock() - if err = d.checkChannel(diff); err != nil { - return + if err := d.checkChannel(diff); err != nil { + return 0, err } return d.readVoltage(diff, 0, d.channelCfgs[diff].gain, d.channelCfgs[diff].dataRate) } @@ -297,41 +299,41 @@ func (d *ADS1x15Driver) ReadDifferenceWithDefaults(diff int) (value float64, err // * 1: Channel 0 - channel 3 // * 2: Channel 1 - channel 3 // * 3: Channel 2 - channel 3 -func (d *ADS1x15Driver) ReadDifference(diff int, gain int, dataRate int) (value float64, err error) { +func (d *ADS1x15Driver) ReadDifference(diff int, gain int, dataRate int) (float64, error) { d.mutex.Lock() defer d.mutex.Unlock() - if err = d.checkChannel(diff); err != nil { - return + if err := d.checkChannel(diff); err != nil { + return 0, err } return d.readVoltage(diff, 0, gain, dataRate) } // ReadWithDefaults reads the voltage at the specified channel (between 0 and 3). // Default values are used for the gain and data rate. The result is in V. -func (d *ADS1x15Driver) ReadWithDefaults(channel int) (value float64, err error) { +func (d *ADS1x15Driver) ReadWithDefaults(channel int) (float64, error) { d.mutex.Lock() defer d.mutex.Unlock() - if err = d.checkChannel(channel); err != nil { - return + if err := d.checkChannel(channel); err != nil { + return 0, err } return d.readVoltage(channel, 0x04, d.channelCfgs[channel].gain, d.channelCfgs[channel].dataRate) } // Read reads the voltage at the specified channel (between 0 and 3). The result is in V. -func (d *ADS1x15Driver) Read(channel int, gain int, dataRate int) (value float64, err error) { +func (d *ADS1x15Driver) Read(channel int, gain int, dataRate int) (float64, error) { d.mutex.Lock() defer d.mutex.Unlock() - if err = d.checkChannel(channel); err != nil { - return + if err := d.checkChannel(channel); err != nil { + return 0, err } return d.readVoltage(channel, 0x04, gain, dataRate) } // AnalogRead returns value from analog reading of specified pin using the default values. -func (d *ADS1x15Driver) AnalogRead(pin string) (value int, err error) { +func (d *ADS1x15Driver) AnalogRead(pin string) (int, error) { d.mutex.Lock() defer d.mutex.Unlock() @@ -350,41 +352,40 @@ func (d *ADS1x15Driver) AnalogRead(pin string) (value int, err error) { channel = 3 default: // read the voltage at a specific pin, compared to the ground + var err error channel, err = strconv.Atoi(pin) if err != nil { - return + return 0, err } channelOffset = 0x04 } - if err = d.checkChannel(channel); err != nil { - return + if err := d.checkChannel(channel); err != nil { + return 0, err } - value, err = d.rawRead(channel, channelOffset, d.channelCfgs[channel].gain, d.channelCfgs[channel].dataRate) - - return + return d.rawRead(channel, channelOffset, d.channelCfgs[channel].gain, d.channelCfgs[channel].dataRate) } -func (d *ADS1x15Driver) readVoltage(channel int, channelOffset int, gain int, dataRate int) (value float64, err error) { +func (d *ADS1x15Driver) readVoltage(channel int, channelOffset int, gain int, dataRate int) (float64, error) { fsr, err := ads1x15GetFullScaleRange(gain) if err != nil { - return + return 0, err } rawValue, err := d.rawRead(channel, channelOffset, gain, dataRate) // Calculate return value in V - value = float64(rawValue) / float64(1<<15) * fsr + value := float64(rawValue) / float64(1<<15) * fsr - return + return value, err } -func (d *ADS1x15Driver) rawRead(channel int, channelOffset int, gain int, dataRate int) (data int, err error) { +func (d *ADS1x15Driver) rawRead(channel int, channelOffset int, gain int, dataRate int) (int, error) { // Validate the passed in data rate (differs between ADS1015 and ADS1115). dataRateBits, err := ads1x15GetDataRateBits(d.dataRates, dataRate) if err != nil { - return + return 0, err } var config uint16 @@ -408,35 +409,35 @@ func (d *ADS1x15Driver) rawRead(channel int, channelOffset int, gain int, dataRa config |= ads1x15ConfigCompQueDisable // Send the config value to start the ADC conversion. - if err = d.writeWordBigEndian(ads1x15PointerConfig, config); err != nil { - return + if err := d.writeWordBigEndian(ads1x15PointerConfig, config); err != nil { + return 0, err } // Wait for the ADC sample to finish based on the sample rate plus a // small offset to be sure (0.1 millisecond). delay := time.Duration(1000000/dataRate+100) * time.Microsecond - if err = d.waitForConversionFinished(delay); err != nil { - return + if err := d.waitForConversionFinished(delay); err != nil { + return 0, err } // Retrieve the result. udata, err := d.readWordBigEndian(ads1x15PointerConversion) if err != nil { - return + return 0, err } // Handle negative values as two's complement return int(twosComplement16Bit(udata)), nil } -func (d *ADS1x15Driver) checkChannel(channel int) (err error) { +func (d *ADS1x15Driver) checkChannel(channel int) error { if channel < 0 || channel > 3 { - err = fmt.Errorf("Invalid channel (%d), must be between 0 and 3", channel) + return fmt.Errorf("Invalid channel (%d), must be between 0 and 3", channel) } - return + return nil } -func (d *ADS1x15Driver) waitForConversionFinished(delay time.Duration) (err error) { +func (d *ADS1x15Driver) waitForConversionFinished(delay time.Duration) error { start := time.Now() for i := 0; i < ads1x15WaitMaxCount; i++ { @@ -444,9 +445,10 @@ func (d *ADS1x15Driver) waitForConversionFinished(delay time.Duration) (err erro // most likely the last try will also not finish, so we stop with an error return fmt.Errorf("The conversion is not finished within %s", time.Since(start)) } - var data uint16 - if data, err = d.readWordBigEndian(ads1x15PointerConfig); err != nil { - return + + data, err := d.readWordBigEndian(ads1x15PointerConfig) + if err != nil { + return err } if ads1x15Debug { log.Printf("ADS1x15Driver: config register state: 0x%X\n", data) @@ -466,16 +468,17 @@ func (d *ADS1x15Driver) waitForConversionFinished(delay time.Duration) (err erro log.Printf("conversion takes %s", elapsed) } - return + return nil } func (d *ADS1x15Driver) writeWordBigEndian(reg uint8, val uint16) error { return d.connection.WriteWordData(reg, swapBytes(val)) } -func (d *ADS1x15Driver) readWordBigEndian(reg uint8) (data uint16, err error) { - if data, err = d.connection.ReadWordData(reg); err != nil { - return +func (d *ADS1x15Driver) readWordBigEndian(reg uint8) (uint16, error) { + data, err := d.connection.ReadWordData(reg) + if err != nil { + return 0, err } return swapBytes(data), err } @@ -492,10 +495,9 @@ func (d *ADS1x15Driver) setChannelGains(gain int) { } } -func ads1x15GetFullScaleRange(gain int) (fsr float64, err error) { - fsr, ok := ads1x15FullScaleRange[gain] - if ok { - return +func ads1x15GetFullScaleRange(gain int) (float64, error) { + if fsr, ok := ads1x15FullScaleRange[gain]; ok { + return fsr, nil } keys := []int{} @@ -503,14 +505,13 @@ func ads1x15GetFullScaleRange(gain int) (fsr float64, err error) { keys = append(keys, k) } sort.Ints(keys) - err = fmt.Errorf("Gain (%d) must be one of: %d", gain, keys) - return + + return 0, fmt.Errorf("Gain (%d) must be one of: %d", gain, keys) } -func ads1x15GetDataRateBits(dataRates map[int]uint16, dataRate int) (bits uint16, err error) { - bits, ok := dataRates[dataRate] - if ok { - return +func ads1x15GetDataRateBits(dataRates map[int]uint16, dataRate int) (uint16, error) { + if bits, ok := dataRates[dataRate]; ok { + return bits, nil } keys := []int{} @@ -518,12 +519,12 @@ func ads1x15GetDataRateBits(dataRates map[int]uint16, dataRate int) (bits uint16 keys = append(keys, k) } sort.Ints(keys) - err = fmt.Errorf("Invalid data rate (%d). Accepted values: %d", dataRate, keys) - return + + return 0, fmt.Errorf("Invalid data rate (%d). Accepted values: %d", dataRate, keys) } // ads1x15BestGainForVoltage returns the gain the most adapted to read up to the specified difference of potential. -func ads1x15BestGainForVoltage(voltage float64) (bestGain int, err error) { +func ads1x15BestGainForVoltage(voltage float64) (int, error) { var max float64 difference := math.MaxFloat64 currentBestGain := -1 @@ -538,10 +539,8 @@ func ads1x15BestGainForVoltage(voltage float64) (bestGain int, err error) { } if currentBestGain < 0 { - err = fmt.Errorf("The maximum voltage which can be read is %f", max) - return + return 0, fmt.Errorf("The maximum voltage which can be read is %f", max) } - bestGain = currentBestGain - return + return currentBestGain, nil } diff --git a/drivers/i2c/ads1x15_driver_test.go b/drivers/i2c/ads1x15_driver_test.go index 3bbe77688..ba524af5b 100644 --- a/drivers/i2c/ads1x15_driver_test.go +++ b/drivers/i2c/ads1x15_driver_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert // ok here package i2c import ( @@ -5,6 +6,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/aio" ) diff --git a/drivers/i2c/adxl345_driver.go b/drivers/i2c/adxl345_driver.go index 5084bd2a6..42d577d36 100644 --- a/drivers/i2c/adxl345_driver.go +++ b/drivers/i2c/adxl345_driver.go @@ -186,39 +186,30 @@ func WithADXL345FullScaleRange(val ADXL345FsRangeConfig) func(Config) { } // UseLowPower change the current rate of the sensor -func (d *ADXL345Driver) UseLowPower(lowPower bool) (err error) { +func (d *ADXL345Driver) UseLowPower(lowPower bool) error { d.mutex.Lock() defer d.mutex.Unlock() d.bwRate.lowPower = lowPower - if err := d.connection.WriteByteData(adxl345Reg_BW_RATE, d.bwRate.toByte()); err != nil { - return err - } - return + return d.connection.WriteByteData(adxl345Reg_BW_RATE, d.bwRate.toByte()) } // SetRate change the current rate of the sensor immediately -func (d *ADXL345Driver) SetRate(rate ADXL345RateConfig) (err error) { +func (d *ADXL345Driver) SetRate(rate ADXL345RateConfig) error { d.mutex.Lock() defer d.mutex.Unlock() d.bwRate.rate = rate - if err := d.connection.WriteByteData(adxl345Reg_BW_RATE, d.bwRate.toByte()); err != nil { - return err - } - return + return d.connection.WriteByteData(adxl345Reg_BW_RATE, d.bwRate.toByte()) } // SetRange change the current range of the sensor immediately -func (d *ADXL345Driver) SetRange(fullScaleRange ADXL345FsRangeConfig) (err error) { +func (d *ADXL345Driver) SetRange(fullScaleRange ADXL345FsRangeConfig) error { d.mutex.Lock() defer d.mutex.Unlock() d.dataFormat.fullScaleRange = fullScaleRange - if err := d.connection.WriteByteData(adxl345Reg_DATA_FORMAT, d.dataFormat.toByte()); err != nil { - return err - } - return + return d.connection.WriteByteData(adxl345Reg_DATA_FORMAT, d.dataFormat.toByte()) } // XYZ returns the adjusted x, y and z axis, unit [g] diff --git a/drivers/i2c/adxl345_driver_test.go b/drivers/i2c/adxl345_driver_test.go index 2888160dd..4fc14d959 100644 --- a/drivers/i2c/adxl345_driver_test.go +++ b/drivers/i2c/adxl345_driver_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -204,9 +205,12 @@ func TestADXL345RawXYZError(t *testing.T) { return 0, errors.New("read error") } // act - _, _, _, err := d.RawXYZ() + x, y, z, err := d.RawXYZ() // assert require.ErrorContains(t, err, "read error") + assert.Equal(t, int16(0), x) + assert.Equal(t, int16(0), y) + assert.Equal(t, int16(0), z) } func TestADXL345XYZ(t *testing.T) { @@ -268,9 +272,12 @@ func TestADXL345XYZError(t *testing.T) { return 0, errors.New("read error") } // act - _, _, _, err := d.XYZ() + x, y, z, err := d.XYZ() // assert require.ErrorContains(t, err, "read error") + assert.InDelta(t, 0.0, x, 0.0) + assert.InDelta(t, 0.0, y, 0.0) + assert.InDelta(t, 0.0, z, 0.0) } func TestADXL345_initialize(t *testing.T) { diff --git a/drivers/i2c/bh1750_driver.go b/drivers/i2c/bh1750_driver.go index a2bbe9c2b..4e470ed14 100644 --- a/drivers/i2c/bh1750_driver.go +++ b/drivers/i2c/bh1750_driver.go @@ -50,27 +50,27 @@ func NewBH1750Driver(c Connector, options ...func(Config)) *BH1750Driver { } // RawSensorData returns the raw value from the bh1750 -func (h *BH1750Driver) RawSensorData() (level int, err error) { +func (h *BH1750Driver) RawSensorData() (int, error) { buf := []byte{0, 0} bytesRead, err := h.connection.Read(buf) - if bytesRead != 2 { - err = errors.New("wrong number of bytes read") - return - } if err != nil { - return + return 0, err } - level = int(buf[0])<<8 | int(buf[1]) + if bytesRead != 2 { + return 0, errors.New("wrong number of bytes read") + } + + level := int(buf[0])<<8 | int(buf[1]) - return + return level, nil } // 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) +func (h *BH1750Driver) Lux() (int, error) { + rawLux, err := h.RawSensorData() + lux := int(float64(rawLux) / 1.2) - return + return lux, err } func (h *BH1750Driver) initialize() error { diff --git a/drivers/i2c/bh1750_driver_test.go b/drivers/i2c/bh1750_driver_test.go index ffa75ee6a..9a8e5cbd5 100644 --- a/drivers/i2c/bh1750_driver_test.go +++ b/drivers/i2c/bh1750_driver_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/i2c/blinkm_driver.go b/drivers/i2c/blinkm_driver.go index ef8711639..072bbc242 100644 --- a/drivers/i2c/blinkm_driver.go +++ b/drivers/i2c/blinkm_driver.go @@ -31,6 +31,7 @@ func NewBlinkMDriver(c Connector, options ...func(Config)) *BlinkMDriver { option(b) } + //nolint:forcetypeassert // ok here b.AddCommand("Rgb", func(params map[string]interface{}) interface{} { red := byte(params["red"].(float64)) green := byte(params["green"].(float64)) @@ -38,6 +39,7 @@ func NewBlinkMDriver(c Connector, options ...func(Config)) *BlinkMDriver { return b.Rgb(red, green, blue) }) + //nolint:forcetypeassert // ok here b.AddCommand("Fade", func(params map[string]interface{}) interface{} { red := byte(params["red"].(float64)) green := byte(params["green"].(float64)) @@ -59,40 +61,40 @@ func NewBlinkMDriver(c Connector, options ...func(Config)) *BlinkMDriver { } // Rgb sets color using r,g,b params -func (b *BlinkMDriver) Rgb(red byte, green byte, blue byte) (err error) { - if _, err = b.connection.Write([]byte("n")); err != nil { - return +func (b *BlinkMDriver) Rgb(red byte, green byte, blue byte) error { + if _, err := b.connection.Write([]byte("n")); err != nil { + return err } - _, err = b.connection.Write([]byte{red, green, blue}) - return + _, err := b.connection.Write([]byte{red, green, blue}) + return err } // Fade removes color using r,g,b params -func (b *BlinkMDriver) Fade(red byte, green byte, blue byte) (err error) { - if _, err = b.connection.Write([]byte("c")); err != nil { - return +func (b *BlinkMDriver) Fade(red byte, green byte, blue byte) error { + if _, err := b.connection.Write([]byte("c")); err != nil { + return err } - _, err = b.connection.Write([]byte{red, green, blue}) - return + _, err := b.connection.Write([]byte{red, green, blue}) + return err } // FirmwareVersion returns version with MAYOR.minor format -func (b *BlinkMDriver) FirmwareVersion() (version string, err error) { - if _, err = b.connection.Write([]byte("Z")); err != nil { - return +func (b *BlinkMDriver) FirmwareVersion() (string, error) { + if _, err := b.connection.Write([]byte("Z")); err != nil { + return "", err } data := []byte{0, 0} read, err := b.connection.Read(data) if read != 2 || err != nil { - return + return "", err } return fmt.Sprintf("%v.%v", data[0], data[1]), nil } // Color returns an array with current rgb color -func (b *BlinkMDriver) Color() (color []byte, err error) { - if _, err = b.connection.Write([]byte("g")); err != nil { - return +func (b *BlinkMDriver) Color() ([]byte, error) { + if _, err := b.connection.Write([]byte("g")); err != nil { + return []byte{}, err } data := []byte{0, 0, 0} read, err := b.connection.Read(data) diff --git a/drivers/i2c/blinkm_driver_test.go b/drivers/i2c/blinkm_driver_test.go index 1818fbbbb..e10cebdfb 100644 --- a/drivers/i2c/blinkm_driver_test.go +++ b/drivers/i2c/blinkm_driver_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert // ok here package i2c import ( @@ -7,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/i2c/bme280_driver.go b/drivers/i2c/bme280_driver.go index d3767cdc1..11d658ce8 100644 --- a/drivers/i2c/bme280_driver.go +++ b/drivers/i2c/bme280_driver.go @@ -123,16 +123,16 @@ func WithBME280HumidityOversampling(val BME280HumidityOversampling) func(Config) } // Humidity returns the current humidity in percentage of relative humidity -func (d *BME280Driver) Humidity() (humidity float32, err error) { +func (d *BME280Driver) Humidity() (float32, error) { d.mutex.Lock() defer d.mutex.Unlock() - var rawH uint32 - if rawH, err = d.rawHumidity(); err != nil { + rawH, err := d.rawHumidity() + if err != nil { return 0.0, err } - humidity = d.calculateHumidity(rawH) - return + humidity := d.calculateHumidity(rawH) + return humidity, nil } func (d *BME280Driver) initializationBME280() error { diff --git a/drivers/i2c/bme280_driver_test.go b/drivers/i2c/bme280_driver_test.go index daf393528..f89e45be2 100644 --- a/drivers/i2c/bme280_driver_test.go +++ b/drivers/i2c/bme280_driver_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -57,15 +58,18 @@ func TestBME280Measurements(t *testing.T) { adaptor.i2cReadImpl = func(b []byte) (int, error) { buf := new(bytes.Buffer) // Values produced by dumping data from actual sensor - if adaptor.written[len(adaptor.written)-1] == bmp280RegCalib00 { - buf.Write([]byte{126, 109, 214, 102, 50, 0, 54, 149, 220, 213, 208, 11, 64, 30, 166, 255, 249, 255, 172, 38, 10, 216, 189, 16}) - } else if adaptor.written[len(adaptor.written)-1] == bme280RegCalibDigH1 { + switch { + case adaptor.written[len(adaptor.written)-1] == bmp280RegCalib00: + buf.Write([]byte{ + 126, 109, 214, 102, 50, 0, 54, 149, 220, 213, 208, 11, 64, 30, 166, 255, 249, 255, 172, 38, 10, 216, 189, 16, + }) + case adaptor.written[len(adaptor.written)-1] == bme280RegCalibDigH1: buf.Write([]byte{75}) - } else if adaptor.written[len(adaptor.written)-1] == bmp280RegTempData { + case adaptor.written[len(adaptor.written)-1] == bmp280RegTempData: buf.Write([]byte{129, 0, 0}) - } else if adaptor.written[len(adaptor.written)-1] == bme280RegCalibDigH2LSB { + case adaptor.written[len(adaptor.written)-1] == bme280RegCalibDigH2LSB: buf.Write([]byte{112, 1, 0, 19, 1, 0, 30}) - } else if adaptor.written[len(adaptor.written)-1] == bme280RegHumidityMSB { + case adaptor.written[len(adaptor.written)-1] == bme280RegHumidityMSB: buf.Write([]byte{111, 83}) } copy(b, buf.Bytes()) @@ -82,11 +86,14 @@ func TestBME280InitH1Error(t *testing.T) { adaptor.i2cReadImpl = func(b []byte) (int, error) { buf := new(bytes.Buffer) // Values produced by dumping data from actual sensor - if adaptor.written[len(adaptor.written)-1] == bmp280RegCalib00 { - buf.Write([]byte{126, 109, 214, 102, 50, 0, 54, 149, 220, 213, 208, 11, 64, 30, 166, 255, 249, 255, 172, 38, 10, 216, 189, 16}) - } else if adaptor.written[len(adaptor.written)-1] == bme280RegCalibDigH1 { + switch { + case adaptor.written[len(adaptor.written)-1] == bmp280RegCalib00: + buf.Write([]byte{ + 126, 109, 214, 102, 50, 0, 54, 149, 220, 213, 208, 11, 64, 30, 166, 255, 249, 255, 172, 38, 10, 216, 189, 16, + }) + case adaptor.written[len(adaptor.written)-1] == bme280RegCalibDigH1: return 0, errors.New("h1 read error") - } else if adaptor.written[len(adaptor.written)-1] == bme280RegCalibDigH2LSB { + case adaptor.written[len(adaptor.written)-1] == bme280RegCalibDigH2LSB: buf.Write([]byte{112, 1, 0, 19, 1, 0, 30}) } copy(b, buf.Bytes()) @@ -101,11 +108,14 @@ func TestBME280InitH2Error(t *testing.T) { adaptor.i2cReadImpl = func(b []byte) (int, error) { buf := new(bytes.Buffer) // Values produced by dumping data from actual sensor - if adaptor.written[len(adaptor.written)-1] == bmp280RegCalib00 { - buf.Write([]byte{126, 109, 214, 102, 50, 0, 54, 149, 220, 213, 208, 11, 64, 30, 166, 255, 249, 255, 172, 38, 10, 216, 189, 16}) - } else if adaptor.written[len(adaptor.written)-1] == bme280RegCalibDigH1 { + switch { + case adaptor.written[len(adaptor.written)-1] == bmp280RegCalib00: + buf.Write([]byte{ + 126, 109, 214, 102, 50, 0, 54, 149, 220, 213, 208, 11, 64, 30, 166, 255, 249, 255, 172, 38, 10, 216, 189, 16, + }) + case adaptor.written[len(adaptor.written)-1] == bme280RegCalibDigH1: buf.Write([]byte{75}) - } else if adaptor.written[len(adaptor.written)-1] == bme280RegCalibDigH2LSB { + case adaptor.written[len(adaptor.written)-1] == bme280RegCalibDigH2LSB: return 0, errors.New("h2 read error") } copy(b, buf.Bytes()) @@ -144,15 +154,18 @@ func TestBME280HumidityNotEnabled(t *testing.T) { adaptor.i2cReadImpl = func(b []byte) (int, error) { buf := new(bytes.Buffer) // Values produced by dumping data from actual sensor - if adaptor.written[len(adaptor.written)-1] == bmp280RegCalib00 { - buf.Write([]byte{126, 109, 214, 102, 50, 0, 54, 149, 220, 213, 208, 11, 64, 30, 166, 255, 249, 255, 172, 38, 10, 216, 189, 16}) - } else if adaptor.written[len(adaptor.written)-1] == bme280RegCalibDigH1 { + switch { + case adaptor.written[len(adaptor.written)-1] == bmp280RegCalib00: + buf.Write([]byte{ + 126, 109, 214, 102, 50, 0, 54, 149, 220, 213, 208, 11, 64, 30, 166, 255, 249, 255, 172, 38, 10, 216, 189, 16, + }) + case adaptor.written[len(adaptor.written)-1] == bme280RegCalibDigH1: buf.Write([]byte{75}) - } else if adaptor.written[len(adaptor.written)-1] == bmp280RegTempData { + case adaptor.written[len(adaptor.written)-1] == bmp280RegTempData: buf.Write([]byte{129, 0, 0}) - } else if adaptor.written[len(adaptor.written)-1] == bme280RegCalibDigH2LSB { + case adaptor.written[len(adaptor.written)-1] == bme280RegCalibDigH2LSB: buf.Write([]byte{112, 1, 0, 19, 1, 0, 30}) - } else if adaptor.written[len(adaptor.written)-1] == bme280RegHumidityMSB { + case adaptor.written[len(adaptor.written)-1] == bme280RegHumidityMSB: buf.Write([]byte{0x80, 0x00}) } copy(b, buf.Bytes()) diff --git a/drivers/i2c/bmp180_driver.go b/drivers/i2c/bmp180_driver.go index a4cd1c085..176945605 100644 --- a/drivers/i2c/bmp180_driver.go +++ b/drivers/i2c/bmp180_driver.go @@ -95,28 +95,28 @@ func WithBMP180OversamplingMode(val BMP180OversamplingMode) func(Config) { } // Temperature returns the current temperature, in celsius degrees. -func (d *BMP180Driver) Temperature() (temp float32, err error) { +func (d *BMP180Driver) Temperature() (float32, error) { d.mutex.Lock() defer d.mutex.Unlock() - var rawTemp int16 - if rawTemp, err = d.rawTemp(); err != nil { + rawTemp, err := d.rawTemp() + if err != nil { return 0, err } return d.calculateTemp(rawTemp), nil } // Pressure returns the current pressure, in pascals. -func (d *BMP180Driver) Pressure() (pressure float32, err error) { +func (d *BMP180Driver) Pressure() (float32, error) { d.mutex.Lock() defer d.mutex.Unlock() - var rawTemp int16 - var rawPressure int32 - if rawTemp, err = d.rawTemp(); err != nil { + rawTemp, err := d.rawTemp() + if err != nil { return 0, err } - if rawPressure, err = d.rawPressure(d.oversampling); err != nil { + rawPressure, err := d.rawPressure(d.oversampling) + if err != nil { return 0, err } return d.calculatePressure(rawTemp, rawPressure, d.oversampling), nil @@ -192,20 +192,24 @@ func (d *BMP180Driver) calculateB5(rawTemp int16) int32 { return x1 + x2 } -func (d *BMP180Driver) rawPressure(oversampling BMP180OversamplingMode) (rawPressure int32, err error) { - if _, err = d.connection.Write([]byte{bmp180RegisterCtl, bmp180CtlPressure + byte(oversampling<<6)}); err != nil { +func (d *BMP180Driver) rawPressure(oversampling BMP180OversamplingMode) (int32, error) { + if _, err := d.connection.Write([]byte{bmp180RegisterCtl, bmp180CtlPressure + byte(oversampling<<6)}); err != nil { return 0, err } time.Sleep(bmp180PauseForReading(oversampling)) ret := make([]byte, 3) - if err = d.connection.ReadBlockData(bmp180RegisterDataMSB, ret); err != nil { + if err := d.connection.ReadBlockData(bmp180RegisterDataMSB, ret); err != nil { return 0, err } - rawPressure = (int32(ret[0])<<16 + int32(ret[1])<<8 + int32(ret[2])) >> (8 - uint(oversampling)) + rawPressure := (int32(ret[0])<<16 + int32(ret[1])<<8 + int32(ret[2])) >> (8 - uint(oversampling)) return rawPressure, nil } -func (d *BMP180Driver) calculatePressure(rawTemp int16, rawPressure int32, oversampling BMP180OversamplingMode) float32 { +func (d *BMP180Driver) calculatePressure( + rawTemp int16, + rawPressure int32, + oversampling BMP180OversamplingMode, +) float32 { b5 := d.calculateB5(rawTemp) b6 := b5 - 4000 x1 := (int32(d.calCoeffs.b2) * (b6 * b6 >> 12)) >> 11 diff --git a/drivers/i2c/bmp180_driver_test.go b/drivers/i2c/bmp180_driver_test.go index e70393718..374e42fd1 100644 --- a/drivers/i2c/bmp180_driver_test.go +++ b/drivers/i2c/bmp180_driver_test.go @@ -10,6 +10,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -49,7 +50,8 @@ func TestBMP180Measurements(t *testing.T) { adaptor.i2cReadImpl = func(b []byte) (int, error) { buf := new(bytes.Buffer) // Values from the datasheet example. - if adaptor.written[len(adaptor.written)-1] == bmp180RegisterAC1MSB { + switch { + case adaptor.written[len(adaptor.written)-1] == bmp180RegisterAC1MSB: _ = binary.Write(buf, binary.BigEndian, int16(408)) _ = binary.Write(buf, binary.BigEndian, int16(-72)) _ = binary.Write(buf, binary.BigEndian, int16(-14383)) @@ -61,9 +63,11 @@ func TestBMP180Measurements(t *testing.T) { _ = binary.Write(buf, binary.BigEndian, int16(-32768)) _ = binary.Write(buf, binary.BigEndian, int16(-8711)) _ = binary.Write(buf, binary.BigEndian, int16(2868)) - } else if adaptor.written[len(adaptor.written)-2] == bmp180CtlTemp && adaptor.written[len(adaptor.written)-1] == bmp180RegisterDataMSB { + case adaptor.written[len(adaptor.written)-2] == bmp180CtlTemp && + adaptor.written[len(adaptor.written)-1] == bmp180RegisterDataMSB: _ = binary.Write(buf, binary.BigEndian, int16(27898)) - } else if adaptor.written[len(adaptor.written)-2] == bmp180CtlPressure && adaptor.written[len(adaptor.written)-1] == bmp180RegisterDataMSB { + case adaptor.written[len(adaptor.written)-2] == bmp180CtlPressure && + adaptor.written[len(adaptor.written)-1] == bmp180RegisterDataMSB: _ = binary.Write(buf, binary.BigEndian, int16(23843)) // XLSB, not used in this test. buf.WriteByte(0) @@ -85,7 +89,8 @@ func TestBMP180TemperatureError(t *testing.T) { adaptor.i2cReadImpl = func(b []byte) (int, error) { buf := new(bytes.Buffer) // Values from the datasheet example. - if adaptor.written[len(adaptor.written)-1] == bmp180RegisterAC1MSB { + switch { + case adaptor.written[len(adaptor.written)-1] == bmp180RegisterAC1MSB: _ = binary.Write(buf, binary.BigEndian, int16(408)) _ = binary.Write(buf, binary.BigEndian, int16(-72)) _ = binary.Write(buf, binary.BigEndian, int16(-14383)) @@ -97,9 +102,11 @@ func TestBMP180TemperatureError(t *testing.T) { _ = binary.Write(buf, binary.BigEndian, int16(-32768)) _ = binary.Write(buf, binary.BigEndian, int16(-8711)) _ = binary.Write(buf, binary.BigEndian, int16(2868)) - } else if adaptor.written[len(adaptor.written)-2] == bmp180CtlTemp && adaptor.written[len(adaptor.written)-1] == bmp180RegisterDataMSB { + case adaptor.written[len(adaptor.written)-2] == bmp180CtlTemp && + adaptor.written[len(adaptor.written)-1] == bmp180RegisterDataMSB: return 0, errors.New("temp error") - } else if adaptor.written[len(adaptor.written)-2] == bmp180CtlPressure && adaptor.written[len(adaptor.written)-1] == bmp180RegisterDataMSB { + case adaptor.written[len(adaptor.written)-2] == bmp180CtlPressure && + adaptor.written[len(adaptor.written)-1] == bmp180RegisterDataMSB: _ = binary.Write(buf, binary.BigEndian, int16(23843)) // XLSB, not used in this test. buf.WriteByte(0) @@ -117,7 +124,8 @@ func TestBMP180PressureError(t *testing.T) { adaptor.i2cReadImpl = func(b []byte) (int, error) { buf := new(bytes.Buffer) // Values from the datasheet example. - if adaptor.written[len(adaptor.written)-1] == bmp180RegisterAC1MSB { + switch { + case adaptor.written[len(adaptor.written)-1] == bmp180RegisterAC1MSB: _ = binary.Write(buf, binary.BigEndian, int16(408)) _ = binary.Write(buf, binary.BigEndian, int16(-72)) _ = binary.Write(buf, binary.BigEndian, int16(-14383)) @@ -129,9 +137,11 @@ func TestBMP180PressureError(t *testing.T) { _ = binary.Write(buf, binary.BigEndian, int16(-32768)) _ = binary.Write(buf, binary.BigEndian, int16(-8711)) _ = binary.Write(buf, binary.BigEndian, int16(2868)) - } else if adaptor.written[len(adaptor.written)-2] == bmp180CtlTemp && adaptor.written[len(adaptor.written)-1] == bmp180RegisterDataMSB { + case adaptor.written[len(adaptor.written)-2] == bmp180CtlTemp && + adaptor.written[len(adaptor.written)-1] == bmp180RegisterDataMSB: _ = binary.Write(buf, binary.BigEndian, int16(27898)) - } else if adaptor.written[len(adaptor.written)-2] == bmp180CtlPressure && adaptor.written[len(adaptor.written)-1] == bmp180RegisterDataMSB { + case adaptor.written[len(adaptor.written)-2] == bmp180CtlPressure && + adaptor.written[len(adaptor.written)-1] == bmp180RegisterDataMSB: return 0, errors.New("press error") } copy(b, buf.Bytes()) diff --git a/drivers/i2c/bmp280_driver.go b/drivers/i2c/bmp280_driver.go index ebf5207d0..3a6f9c6d0 100644 --- a/drivers/i2c/bmp280_driver.go +++ b/drivers/i2c/bmp280_driver.go @@ -161,29 +161,30 @@ func WithBMP280IIRFilter(val BMP280IIRFilter) func(Config) { } // Temperature returns the current temperature, in celsius degrees. -func (d *BMP280Driver) Temperature() (temp float32, err error) { +func (d *BMP280Driver) Temperature() (float32, error) { d.mutex.Lock() defer d.mutex.Unlock() - var rawT int32 - if rawT, err = d.rawTemp(); err != nil { + rawT, err := d.rawTemp() + if err != nil { return 0.0, err } - temp, _ = d.calculateTemp(rawT) - return + temp, _ := d.calculateTemp(rawT) + return temp, nil } // Pressure returns the current barometric pressure, in Pa -func (d *BMP280Driver) Pressure() (press float32, err error) { +func (d *BMP280Driver) Pressure() (float32, error) { d.mutex.Lock() defer d.mutex.Unlock() - var rawT, rawP int32 - if rawT, err = d.rawTemp(); err != nil { + rawT, err := d.rawTemp() + if err != nil { return 0.0, err } - if rawP, err = d.rawPressure(); err != nil { + rawP, err := d.rawPressure() + if err != nil { return 0.0, err } _, tFine := d.calculateTemp(rawT) @@ -195,12 +196,12 @@ func (d *BMP280Driver) Pressure() (press float32, err error) { // Calculation is based on code from Adafruit BME280 library // // https://github.com/adafruit/Adafruit_BME280_Library -func (d *BMP280Driver) Altitude() (alt float32, err error) { +func (d *BMP280Driver) Altitude() (float32, error) { atmP, _ := d.Pressure() atmP /= 100.0 - alt = float32(44330.0 * (1.0 - math.Pow(float64(atmP/bmp280SeaLevelPressure), 0.1903))) + alt := float32(44330.0 * (1.0 - math.Pow(float64(atmP/bmp280SeaLevelPressure), 0.1903))) - return + return alt, nil } // initialization reads the calibration coefficients. @@ -300,7 +301,8 @@ func (d *BMP280Driver) rawPressure() (int32, error) { func (d *BMP280Driver) calculateTemp(rawTemp int32) (float32, int32) { tcvar1 := ((float32(rawTemp) / 16384.0) - (float32(d.calCoeffs.t1) / 1024.0)) * float32(d.calCoeffs.t2) - tcvar2 := (((float32(rawTemp) / 131072.0) - (float32(d.calCoeffs.t1) / 8192.0)) * ((float32(rawTemp) / 131072.0) - float32(d.calCoeffs.t1)/8192.0)) * float32(d.calCoeffs.t3) + tcvar2 := (((float32(rawTemp) / 131072.0) - (float32(d.calCoeffs.t1) / 8192.0)) * ((float32(rawTemp) / 131072.0) - + float32(d.calCoeffs.t1)/8192.0)) * float32(d.calCoeffs.t3) temperatureComp := (tcvar1 + tcvar2) / 5120.0 tFine := int32(tcvar1 + tcvar2) diff --git a/drivers/i2c/bmp280_driver_test.go b/drivers/i2c/bmp280_driver_test.go index 04ae5e4d2..17bdec308 100644 --- a/drivers/i2c/bmp280_driver_test.go +++ b/drivers/i2c/bmp280_driver_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -77,11 +78,14 @@ func TestBMP280Measurements(t *testing.T) { adaptor.i2cReadImpl = func(b []byte) (int, error) { buf := new(bytes.Buffer) // Values produced by dumping data from actual sensor - if adaptor.written[len(adaptor.written)-1] == bmp280RegCalib00 { - buf.Write([]byte{126, 109, 214, 102, 50, 0, 54, 149, 220, 213, 208, 11, 64, 30, 166, 255, 249, 255, 172, 38, 10, 216, 189, 16}) - } else if adaptor.written[len(adaptor.written)-1] == bmp280RegTempData { + switch { + case adaptor.written[len(adaptor.written)-1] == bmp280RegCalib00: + buf.Write([]byte{ + 126, 109, 214, 102, 50, 0, 54, 149, 220, 213, 208, 11, 64, 30, 166, 255, 249, 255, 172, 38, 10, 216, 189, 16, + }) + case adaptor.written[len(adaptor.written)-1] == bmp280RegTempData: buf.Write([]byte{128, 243, 0}) - } else if adaptor.written[len(adaptor.written)-1] == bmp280RegPressureData { + case adaptor.written[len(adaptor.written)-1] == bmp280RegPressureData: buf.Write([]byte{77, 23, 48}) } copy(b, buf.Bytes()) diff --git a/drivers/i2c/bmp388_driver.go b/drivers/i2c/bmp388_driver.go index a5dda145a..95a49e323 100644 --- a/drivers/i2c/bmp388_driver.go +++ b/drivers/i2c/bmp388_driver.go @@ -63,7 +63,7 @@ const ( bmp388CMDReserved = 0x00 // reserved, no command bmp388CMDExtModeEnMiddle = 0x34 bmp388CMDFifoFlush = 0xB0 // clears all data in the FIFO, does not change FIFO_CONFIG registers - bmp388CMDSoftReset = 0xB6 // triggers a reset, all user configuration settings are overwritten with their default state + bmp388CMDSoftReset = 0xB6 // triggers a reset, all user configuration settings are overwritten with defaults bmp388SeaLevelPressure = 1013.25 ) @@ -132,66 +132,68 @@ func WithBMP388IIRFilter(val BMP388IIRFilter) func(Config) { } // Temperature returns the current temperature, in celsius degrees. -func (d *BMP388Driver) Temperature(accuracy BMP388Accuracy) (temp float32, err error) { +func (d *BMP388Driver) Temperature(accuracy BMP388Accuracy) (float32, error) { d.mutex.Lock() defer d.mutex.Unlock() - var rawT int32 - mode := d.ctrlPwrMode<<4 | bmp388PWRCTRLPressEnableBit | bmp388PWRCTRLTempEnableBit - if err = d.connection.WriteByteData(bmp388RegPWRCTRL, mode); err != nil { + if err := d.connection.WriteByteData(bmp388RegPWRCTRL, mode); err != nil { return 0, err } // Set Accuracy for temperature - if err = d.connection.WriteByteData(bmp388RegOSR, uint8(accuracy<<3)); err != nil { + if err := d.connection.WriteByteData(bmp388RegOSR, uint8(accuracy<<3)); err != nil { return 0, err } - if rawT, err = d.rawTemp(); err != nil { + rawT, err := d.rawTemp() + if err != nil { return 0.0, err } - temp = d.calculateTemp(rawT) - return + + temp := d.calculateTemp(rawT) + + return temp, nil } // Pressure returns the current barometric pressure, in Pa -func (d *BMP388Driver) Pressure(accuracy BMP388Accuracy) (press float32, err error) { +func (d *BMP388Driver) Pressure(accuracy BMP388Accuracy) (float32, error) { d.mutex.Lock() defer d.mutex.Unlock() - var rawT, rawP int32 - mode := d.ctrlPwrMode<<4 | bmp388PWRCTRLPressEnableBit | bmp388PWRCTRLTempEnableBit - if err = d.connection.WriteByteData(bmp388RegPWRCTRL, mode); err != nil { + if err := d.connection.WriteByteData(bmp388RegPWRCTRL, mode); err != nil { return 0, err } // Set Standard Accuracy for pressure - if err = d.connection.WriteByteData(bmp388RegOSR, uint8(accuracy)); err != nil { + if err := d.connection.WriteByteData(bmp388RegOSR, uint8(accuracy)); err != nil { return 0, err } - if rawT, err = d.rawTemp(); err != nil { + rawT, err := d.rawTemp() + if err != nil { return 0.0, err } - if rawP, err = d.rawPressure(); err != nil { + rawP, err := d.rawPressure() + if err != nil { return 0.0, err } tLin := d.calculateTemp(rawT) + return d.calculatePress(rawP, float64(tLin)), nil } // Altitude returns the current altitude in meters based on the // current barometric pressure and estimated pressure at sea level. // https://www.weather.gov/media/epz/wxcalc/pressureAltitude.pdf -func (d *BMP388Driver) Altitude(accuracy BMP388Accuracy) (alt float32, err error) { +func (d *BMP388Driver) Altitude(accuracy BMP388Accuracy) (float32, error) { atmP, _ := d.Pressure(accuracy) atmP /= 100.0 - alt = float32(44307.0 * (1.0 - math.Pow(float64(atmP/bmp388SeaLevelPressure), 0.190284))) + alt := float32(44307.0 * (1.0 - math.Pow(float64(atmP/bmp388SeaLevelPressure), 0.190284))) - return + return alt, nil } // initialization reads the calibration coefficients. diff --git a/drivers/i2c/bmp388_driver_test.go b/drivers/i2c/bmp388_driver_test.go index ea2b25a14..41fb6cb79 100644 --- a/drivers/i2c/bmp388_driver_test.go +++ b/drivers/i2c/bmp388_driver_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -73,7 +74,9 @@ func TestBMP388Measurements(t *testing.T) { _ = binary.Write(buf, binary.LittleEndian, uint8(0x50)) case bmp388RegCalib00: // Values produced by dumping data from actual sensor - buf.Write([]byte{36, 107, 156, 73, 246, 104, 255, 189, 245, 35, 0, 151, 101, 184, 122, 243, 246, 211, 64, 14, 196, 0, 0, 0}) + buf.Write([]byte{ + 36, 107, 156, 73, 246, 104, 255, 189, 245, 35, 0, 151, 101, 184, 122, 243, 246, 211, 64, 14, 196, 0, 0, 0, + }) case bmp388RegTempData: buf.Write([]byte{0, 28, 127}) case bmp388RegPressureData: @@ -163,7 +166,9 @@ func TestBMP388_initialization(t *testing.T) { wantConfRegVal = uint8(0x00) // no filter ) // Values produced by dumping data from actual sensor - returnRead := []byte{36, 107, 156, 73, 246, 104, 255, 189, 245, 35, 0, 151, 101, 184, 122, 243, 246, 211, 64, 14, 196, 0, 0, 0} + returnRead := []byte{ + 36, 107, 156, 73, 246, 104, 255, 189, 245, 35, 0, 151, 101, 184, 122, 243, 246, 211, 64, 14, 196, 0, 0, 0, + } numCallsRead := 0 a.i2cReadImpl = func(b []byte) (int, error) { numCallsRead++ diff --git a/drivers/i2c/ccs811_driver.go b/drivers/i2c/ccs811_driver.go index 8434d770d..c55c8e3d5 100644 --- a/drivers/i2c/ccs811_driver.go +++ b/drivers/i2c/ccs811_driver.go @@ -9,7 +9,8 @@ import ( // CCS811DriveMode type type CCS811DriveMode uint8 -// Operating modes which dictate how often measurements are being made. If 0x00 is used as an operating mode, measurements will be disabled +// Operating modes which dictate how often measurements are being made. If 0x00 is used as an operating mode, +// measurements will be disabled const ( CCS811DriveModeIdle CCS811DriveMode = 0x00 CCS811DriveMode1Sec CCS811DriveMode = 0x01 @@ -24,11 +25,13 @@ const ( 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. + // 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. 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 @@ -42,11 +45,14 @@ const ( ccs811RegHwID = 0x20 // 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 @@ -58,7 +64,8 @@ const ( 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 +// 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 HasError byte @@ -93,7 +100,7 @@ type CCS811MeasMode struct { driveMode CCS811DriveMode } -// NewCCS811MeasMode returns a new instance of the package ccs811 measurement mode configuration. This represents the desired initial +// NewCCS811MeasMode returns a new instance of the measurement mode configuration. This represents the desired initial // state of the measurement mode register. func NewCCS811MeasMode() *CCS811MeasMode { return &CCS811MeasMode{ @@ -240,7 +247,8 @@ func (d *CCS811Driver) GetGasData() (uint16, uint16, error) { return 0, 0, err } - // Bit masks defined by https://ams.com/documents/20143/36005/CCS811_AN000369_2-00.pdf/25d0db9a-92b9-fa7f-362c-a7a4d1e292be#page=14 + // Bit masks defined by + // https://ams.com/documents/20143/36005/CCS811_AN000369_2-00.pdf/25d0db9a-92b9-fa7f-362c-a7a4d1e292be#page=14 eco2 := (uint16(data[0]) << 8) | uint16(data[1]) tvoC := (uint16(data[2]) << 8) | uint16(data[3]) diff --git a/drivers/i2c/ccs811_driver_test.go b/drivers/i2c/ccs811_driver_test.go index f8abcb746..d205a19b3 100644 --- a/drivers/i2c/ccs811_driver_test.go +++ b/drivers/i2c/ccs811_driver_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/i2c/drv2605l_driver.go b/drivers/i2c/drv2605l_driver.go index 5adbbaf17..a29995bc6 100644 --- a/drivers/i2c/drv2605l_driver.go +++ b/drivers/i2c/drv2605l_driver.go @@ -98,7 +98,7 @@ func NewDRV2605LDriver(c Connector, options ...func(Config)) *DRV2605LDriver { // SetMode sets the device in one of the eight modes as described in the // datasheet. Defaults to mode 0, internal trig. -func (d *DRV2605LDriver) SetMode(newMode DRV2605Mode) (err error) { +func (d *DRV2605LDriver) SetMode(newMode DRV2605Mode) error { mode, err := d.connection.ReadByteData(drv2605RegMode) if err != nil { return err @@ -115,7 +115,7 @@ func (d *DRV2605LDriver) SetMode(newMode DRV2605Mode) (err error) { } // SetStandbyMode controls device low power mode -func (d *DRV2605LDriver) SetStandbyMode(standby bool) (err error) { +func (d *DRV2605LDriver) SetStandbyMode(standby bool) error { modeVal, err := d.connection.ReadByteData(drv2605RegMode) if err != nil { return err @@ -133,16 +133,15 @@ func (d *DRV2605LDriver) SetStandbyMode(standby bool) (err error) { // SelectLibrary selects which waveform library to play from, 1-7. // See datasheet for more info. -func (d *DRV2605LDriver) SelectLibrary(library uint8) (err error) { - err = d.connection.WriteByteData(drv2605RegLibrary, library&0x7) - return err +func (d *DRV2605LDriver) SelectLibrary(library uint8) error { + return d.connection.WriteByteData(drv2605RegLibrary, library&0x7) } // GetPauseWaveform returns a special waveform ID used in SetSequence() to encode // pauses between waveforms. Time is specified in tens of milliseconds // ranging from 0ms (delayTime10MS = 0) to 1270ms (delayTime10MS = 127). // Times out of range are clipped to fit. -func (d *DRV2605LDriver) GetPauseWaveform(delayTime10MS uint8) (pauseID uint8) { +func (d *DRV2605LDriver) GetPauseWaveform(delayTime10MS uint8) uint8 { if delayTime10MS > 127 { delayTime10MS = 127 } @@ -156,7 +155,7 @@ func (d *DRV2605LDriver) GetPauseWaveform(delayTime10MS uint8) (pauseID uint8) { // sequences will be truncated. // A waveform id of zero marks the end of the sequence. // Pauses can be encoded using GetPauseWaveform(). -func (d *DRV2605LDriver) SetSequence(waveforms []uint8) (err error) { +func (d *DRV2605LDriver) SetSequence(waveforms []uint8) error { if len(waveforms) < 8 { waveforms = append(waveforms, 0) } @@ -164,26 +163,26 @@ func (d *DRV2605LDriver) SetSequence(waveforms []uint8) (err error) { waveforms = waveforms[0:8] } for i, w := range waveforms { - if err = d.connection.WriteByteData(uint8(drv2605RegWaveSeq1+i), w); err != nil { + if err := d.connection.WriteByteData(uint8(drv2605RegWaveSeq1+i), w); err != nil { return err } } + return nil } // Go plays the current sequence of waveforms. -func (d *DRV2605LDriver) Go() (err error) { - err = d.connection.WriteByteData(drv2605RegGo, 1) - return err +func (d *DRV2605LDriver) Go() error { + return d.connection.WriteByteData(drv2605RegGo, 1) } -func (d *DRV2605LDriver) writeByteRegisters(regValPairs []struct{ reg, val uint8 }) (err error) { +func (d *DRV2605LDriver) writeByteRegisters(regValPairs []struct{ reg, val uint8 }) error { for _, rv := range regValPairs { - if err = d.connection.WriteByteData(rv.reg, rv.val); err != nil { - break + if err := d.connection.WriteByteData(rv.reg, rv.val); err != nil { + return err } } - return err + return nil } func (d *DRV2605LDriver) initialize() error { @@ -215,15 +214,16 @@ func (d *DRV2605LDriver) initialize() error { }) } -func (d *DRV2605LDriver) shutdown() (err error) { +func (d *DRV2605LDriver) shutdown() error { if d.connection != nil { // stop playback - if err = d.connection.WriteByteData(drv2605RegGo, 0); err != nil { + if err := d.connection.WriteByteData(drv2605RegGo, 0); err != nil { return err } // enter standby return d.SetStandbyMode(true) } - return + + return nil } diff --git a/drivers/i2c/drv2605l_driver_test.go b/drivers/i2c/drv2605l_driver_test.go index e8295db7b..0c9b6b54b 100644 --- a/drivers/i2c/drv2605l_driver_test.go +++ b/drivers/i2c/drv2605l_driver_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -64,7 +65,8 @@ func TestDRV2605LHalt(t *testing.T) { d, a := initTestDRV2605LDriverWithStubbedAdaptor() a.written = []byte{} require.NoError(t, d.Halt()) - assert.Equal(t, append(append(writeStopPlaybackData, readCurrentStandbyModeData), writeNewStandbyModeData...), a.written) + assert.Equal(t, append(append(writeStopPlaybackData, readCurrentStandbyModeData), writeNewStandbyModeData...), + a.written) } func TestDRV2605LGetPause(t *testing.T) { diff --git a/drivers/i2c/generic_driver_test.go b/drivers/i2c/generic_driver_test.go index fdb490e69..e522b216d 100644 --- a/drivers/i2c/generic_driver_test.go +++ b/drivers/i2c/generic_driver_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/i2c/grove_drivers_test.go b/drivers/i2c/grove_drivers_test.go index 19f755897..7da5d5872 100644 --- a/drivers/i2c/grove_drivers_test.go +++ b/drivers/i2c/grove_drivers_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "gobot.io/x/gobot/v2" ) @@ -13,9 +14,9 @@ var ( _ gobot.Driver = (*GroveAccelerometerDriver)(nil) ) -func initTestGroveLcdDriver() (driver *GroveLcdDriver) { - driver, _ = initGroveLcdDriverWithStubbedAdaptor() - return +func initTestGroveLcdDriver() *GroveLcdDriver { + d, _ := initGroveLcdDriverWithStubbedAdaptor() + return d } func initGroveLcdDriverWithStubbedAdaptor() (*GroveLcdDriver, *i2cTestAdaptor) { @@ -23,9 +24,9 @@ func initGroveLcdDriverWithStubbedAdaptor() (*GroveLcdDriver, *i2cTestAdaptor) { return NewGroveLcdDriver(adaptor), adaptor } -func initTestGroveAccelerometerDriver() (driver *GroveAccelerometerDriver) { - driver, _ = initGroveAccelerometerDriverWithStubbedAdaptor() - return +func initTestGroveAccelerometerDriver() *GroveAccelerometerDriver { + d, _ := initGroveAccelerometerDriverWithStubbedAdaptor() + return d } func initGroveAccelerometerDriverWithStubbedAdaptor() (*GroveAccelerometerDriver, *i2cTestAdaptor) { diff --git a/drivers/i2c/grovepi_driver.go b/drivers/i2c/grovepi_driver.go index bc5a799a4..204ba51e0 100644 --- a/drivers/i2c/grovepi_driver.go +++ b/drivers/i2c/grovepi_driver.go @@ -70,7 +70,7 @@ func (d *GrovePiDriver) Finalize() error { } // AnalogRead returns value from analog pin implementing the AnalogReader interface. -func (d *GrovePiDriver) AnalogRead(pin string) (value int, err error) { +func (d *GrovePiDriver) AnalogRead(pin string) (int, error) { d.mutex.Lock() defer d.mutex.Unlock() @@ -171,6 +171,8 @@ func (d *GrovePiDriver) FirmwareVersionRead() (string, error) { // DHTRead performs a read temperature and humidity sensors with duration >=2 millisecond. // DHT11 (blue): sensorType=0 // DHT22 (white): sensorTyp=1 +// +//nolint:nonamedreturns // is sufficient here func (d *GrovePiDriver) DHTRead(pin string, sensorType byte, duration int) (temp float32, hum float32, err error) { d.mutex.Lock() defer d.mutex.Unlock() @@ -186,13 +188,13 @@ func (d *GrovePiDriver) DHTRead(pin string, sensorType byte, duration int) (temp buf := []byte{commandReadDHT, byte(pinNum), sensorType, 0} if _, err = d.connection.Write(buf); err != nil { - return + return 0, 0, err } time.Sleep(time.Duration(duration) * time.Millisecond) data := make([]byte, 9) if err = d.readForCommand(commandReadDHT, data); err != nil { - return + return 0, 0, err } temp = float32Of4BytesLittleEndian(data[1:5]) @@ -211,7 +213,7 @@ func (d *GrovePiDriver) DHTRead(pin string, sensorType byte, duration int) (temp hum = 0 } - return + return temp, hum, err } // DigitalWrite writes a value to a specific digital pin implementing the DigitalWriter interface. diff --git a/drivers/i2c/grovepi_driver_test.go b/drivers/i2c/grovepi_driver_test.go index cd6ed5682..ae8a1b97b 100644 --- a/drivers/i2c/grovepi_driver_test.go +++ b/drivers/i2c/grovepi_driver_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/aio" "gobot.io/x/gobot/v2/drivers/gpio" @@ -142,7 +143,7 @@ func TestGrovePiSomeRead(t *testing.T) { _ = g.Start() a.written = []byte{} // reset writes of former test and start numCallsRead := 0 - a.i2cReadImpl = func(bytes []byte) (i int, e error) { + a.i2cReadImpl = func(bytes []byte) (int, error) { numCallsRead++ copy(bytes, tc.simResponse[numCallsRead-1]) return len(tc.simResponse[numCallsRead-1]), nil @@ -205,7 +206,7 @@ func TestGrovePiSomeWrite(t *testing.T) { g, a := initGrovePiDriverWithStubbedAdaptor() _ = g.Start() a.written = []byte{} // reset writes of former test and start - a.i2cReadImpl = func(bytes []byte) (i int, e error) { + a.i2cReadImpl = func(bytes []byte) (int, error) { copy(bytes, tc.simResponse) return len(bytes), nil } diff --git a/drivers/i2c/helpers_test.go b/drivers/i2c/helpers_test.go index b4378cac7..0a043d744 100644 --- a/drivers/i2c/helpers_test.go +++ b/drivers/i2c/helpers_test.go @@ -41,13 +41,13 @@ func (t *i2cTestAdaptor) Testi2cWriteImpl(f func([]byte) (int, error)) { t.i2cWriteImpl = f } -func (t *i2cTestAdaptor) Read(b []byte) (count int, err error) { +func (t *i2cTestAdaptor) Read(b []byte) (int, error) { t.mtx.Lock() defer t.mtx.Unlock() return t.i2cReadImpl(b) } -func (t *i2cTestAdaptor) Write(b []byte) (count int, err error) { +func (t *i2cTestAdaptor) Write(b []byte) (int, error) { t.mtx.Lock() defer t.mtx.Unlock() t.written = append(t.written, b...) @@ -58,36 +58,36 @@ func (t *i2cTestAdaptor) Close() error { return nil } -func (t *i2cTestAdaptor) ReadByte() (val byte, err error) { +func (t *i2cTestAdaptor) ReadByte() (byte, error) { t.mtx.Lock() defer t.mtx.Unlock() bytes := []byte{0} - if err = t.readBytes(bytes); err != nil { - return + if err := t.readBytes(bytes); err != nil { + return 0, err } - val = bytes[0] - return + val := bytes[0] + return val, nil } -func (t *i2cTestAdaptor) ReadByteData(reg uint8) (val uint8, err error) { +func (t *i2cTestAdaptor) ReadByteData(reg uint8) (uint8, error) { t.mtx.Lock() defer t.mtx.Unlock() - if err = t.writeBytes([]byte{reg}); err != nil { - return + if err := t.writeBytes([]byte{reg}); err != nil { + return 0, err } bytes := []byte{0} - if err = t.readBytes(bytes); err != nil { - return + if err := t.readBytes(bytes); err != nil { + return 0, err } - val = bytes[0] - return + val := bytes[0] + return val, nil } -func (t *i2cTestAdaptor) ReadWordData(reg uint8) (val uint16, err error) { +func (t *i2cTestAdaptor) ReadWordData(reg uint8) (uint16, error) { t.mtx.Lock() defer t.mtx.Unlock() - if err = t.writeBytes([]byte{reg}); err != nil { - return + if err := t.writeBytes([]byte{reg}); err != nil { + return 0, err } bytes := []byte{0, 0} bytesRead, err := t.i2cReadImpl(bytes) @@ -98,14 +98,14 @@ func (t *i2cTestAdaptor) ReadWordData(reg uint8) (val uint16, err error) { return 0, fmt.Errorf("Buffer underrun") } low, high := bytes[0], bytes[1] - return (uint16(high) << 8) | uint16(low), err + return (uint16(high) << 8) | uint16(low), nil } -func (t *i2cTestAdaptor) ReadBlockData(reg uint8, b []byte) (err error) { +func (t *i2cTestAdaptor) ReadBlockData(reg uint8, b []byte) error { t.mtx.Lock() defer t.mtx.Unlock() - if err = t.writeBytes([]byte{reg}); err != nil { - return + if err := t.writeBytes([]byte{reg}); err != nil { + return err } return t.readBytes(b) } @@ -116,7 +116,7 @@ func (t *i2cTestAdaptor) WriteByte(val byte) error { return t.writeBytes([]byte{val}) } -func (t *i2cTestAdaptor) WriteByteData(reg uint8, val uint8) (err error) { +func (t *i2cTestAdaptor) WriteByteData(reg uint8, val uint8) error { t.mtx.Lock() defer t.mtx.Unlock() bytes := []byte{reg, val} @@ -156,7 +156,7 @@ func (t *i2cTestAdaptor) WriteBytes(b []byte) error { return t.writeBytes(b) } -func (t *i2cTestAdaptor) GetI2cConnection(address int, bus int) (connection Connection, err error) { +func (t *i2cTestAdaptor) GetI2cConnection(address int, bus int) (Connection, error) { if t.i2cConnectErr { return nil, errors.New("Invalid i2c connection") } @@ -169,10 +169,10 @@ func (t *i2cTestAdaptor) DefaultI2cBus() int { return 0 } -func (t *i2cTestAdaptor) Name() string { return t.name } -func (t *i2cTestAdaptor) SetName(n string) { t.name = n } -func (t *i2cTestAdaptor) Connect() (err error) { return } -func (t *i2cTestAdaptor) Finalize() (err error) { return } +func (t *i2cTestAdaptor) Name() string { return t.name } +func (t *i2cTestAdaptor) SetName(n string) { t.name = n } +func (t *i2cTestAdaptor) Connect() error { return nil } +func (t *i2cTestAdaptor) Finalize() error { return nil } func newI2cTestAdaptor() *i2cTestAdaptor { return &i2cTestAdaptor{ diff --git a/drivers/i2c/hmc5883l_driver.go b/drivers/i2c/hmc5883l_driver.go index 395ab8431..c43f212ca 100644 --- a/drivers/i2c/hmc5883l_driver.go +++ b/drivers/i2c/hmc5883l_driver.go @@ -203,6 +203,8 @@ func WithHMC5883LGain(val int) func(Config) { } // Read reads the values X, Y, Z in Gauss +// +//nolint:nonamedreturns // is sufficient here func (h *HMC5883LDriver) Read() (x float64, y float64, z float64, err error) { h.mutex.Lock() defer h.mutex.Unlock() @@ -215,26 +217,27 @@ func (h *HMC5883LDriver) Read() (x float64, y float64, z float64, err error) { } // Heading returns the current heading in radians -func (h *HMC5883LDriver) Heading() (heading float64, err error) { +func (h *HMC5883LDriver) Heading() (float64, error) { h.mutex.Lock() defer h.mutex.Unlock() - var x, y int16 - x, y, _, err = h.readRawData() + x, y, _, err := h.readRawData() if err != nil { - return + return 0, err } - heading = math.Atan2(float64(y), float64(x)) + heading := math.Atan2(float64(y), float64(x)) if heading > 2*math.Pi { heading -= 2 * math.Pi } if heading < 0 { heading += 2 * math.Pi } - return + return heading, nil } // readRawData reads the raw values from the X, Y, and Z registers +// +//nolint:nonamedreturns // sufficient here func (h *HMC5883LDriver) readRawData() (x int16, y int16, z int16, err error) { // read the data, starting from the initial register data := make([]byte, 6) @@ -249,7 +252,7 @@ func (h *HMC5883LDriver) readRawData() (x int16, y int16, z int16, err error) { return twosComplement16Bit(unsignedX), twosComplement16Bit(unsignedY), twosComplement16Bit(unsignedZ), nil } -func (h *HMC5883LDriver) initialize() (err error) { +func (h *HMC5883LDriver) initialize() error { regA := hmc5883lMeasurementFlowBits[h.applyBias] regA |= hmc5883lOutputRateBits[h.outputRate] << 2 regA |= hmc5883lSamplesAvgBits[h.samplesAvg] << 5 @@ -260,15 +263,13 @@ func (h *HMC5883LDriver) initialize() (err error) { if err := h.connection.WriteByteData(hmc5883lRegB, uint8(regB)); err != nil { return err } - if err := h.connection.WriteByteData(hmc5883lRegMode, uint8(h.measurementMode)); err != nil { - return err - } - return + + return h.connection.WriteByteData(hmc5883lRegMode, uint8(h.measurementMode)) } -func hmc5883lValidateSamplesAveraged(samplesAvg int) (err error) { +func hmc5883lValidateSamplesAveraged(samplesAvg int) error { if _, ok := hmc5883lSamplesAvgBits[uint8(samplesAvg)]; ok { - return + return nil } keys := []int{} @@ -276,13 +277,13 @@ func hmc5883lValidateSamplesAveraged(samplesAvg int) (err error) { keys = append(keys, int(k)) } sort.Ints(keys) - err = fmt.Errorf("Samples averaged must be one of: %d", keys) - return + + return fmt.Errorf("Samples averaged must be one of: %d", keys) } -func hmc5883lValidateOutputRate(outputRate int) (err error) { +func hmc5883lValidateOutputRate(outputRate int) error { if _, ok := hmc5883lOutputRateBits[uint32(outputRate)]; ok { - return + return nil } keys := []int{} @@ -290,13 +291,13 @@ func hmc5883lValidateOutputRate(outputRate int) (err error) { keys = append(keys, int(k)) } sort.Ints(keys) - err = fmt.Errorf("Data output rate must be one of: %d", keys) - return + + return fmt.Errorf("Data output rate must be one of: %d", keys) } -func hmc5883lValidateApplyBias(applyBias int) (err error) { +func hmc5883lValidateApplyBias(applyBias int) error { if _, ok := hmc5883lMeasurementFlowBits[int8(applyBias)]; ok { - return + return nil } keys := []int{} @@ -304,13 +305,13 @@ func hmc5883lValidateApplyBias(applyBias int) (err error) { keys = append(keys, int(k)) } sort.Ints(keys) - err = fmt.Errorf("Apply measurement bias must be one of: %d", keys) - return + + return fmt.Errorf("Apply measurement bias must be one of: %d", keys) } -func hmc5883lValidateGain(gain int) (err error) { +func hmc5883lValidateGain(gain int) error { if _, ok := hmc5883lGainBits[float64(gain)]; ok { - return + return nil } keys := []int{} @@ -318,6 +319,6 @@ func hmc5883lValidateGain(gain int) (err error) { keys = append(keys, int(k)) } sort.Ints(keys) - err = fmt.Errorf("Gain must be one of: %d", keys) - return + + return fmt.Errorf("Gain must be one of: %d", keys) } diff --git a/drivers/i2c/hmc5883l_driver_test.go b/drivers/i2c/hmc5883l_driver_test.go index b62ce07d8..1b512ff20 100644 --- a/drivers/i2c/hmc5883l_driver_test.go +++ b/drivers/i2c/hmc5883l_driver_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/i2c/hmc6352_driver.go b/drivers/i2c/hmc6352_driver.go index 8dd8c43f3..d08ccc48a 100644 --- a/drivers/i2c/hmc6352_driver.go +++ b/drivers/i2c/hmc6352_driver.go @@ -30,22 +30,21 @@ func NewHMC6352Driver(c Connector, options ...func(Config)) *HMC6352Driver { } // Heading returns the current heading -func (h *HMC6352Driver) Heading() (heading uint16, err error) { - if _, err = h.connection.Write([]byte("A")); err != nil { - return +func (h *HMC6352Driver) Heading() (uint16, error) { + if _, err := h.connection.Write([]byte("A")); err != nil { + return 0, err } buf := []byte{0, 0} bytesRead, err := h.connection.Read(buf) if err != nil { - return + return 0, err } if bytesRead == 2 { - heading = (uint16(buf[1]) + uint16(buf[0])*256) / 10 - return + heading := (uint16(buf[1]) + uint16(buf[0])*256) / 10 + return heading, nil } - err = ErrNotEnoughBytes - return + return 0, ErrNotEnoughBytes } func (h *HMC6352Driver) initialize() error { diff --git a/drivers/i2c/hmc6352_driver_test.go b/drivers/i2c/hmc6352_driver_test.go index 908fb422b..770d1c446 100644 --- a/drivers/i2c/hmc6352_driver_test.go +++ b/drivers/i2c/hmc6352_driver_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/i2c/i2c_config_test.go b/drivers/i2c/i2c_config_test.go index 7c9a2fbb2..28dc37eeb 100644 --- a/drivers/i2c/i2c_config_test.go +++ b/drivers/i2c/i2c_config_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert // ok here package i2c import ( diff --git a/drivers/i2c/i2c_connection.go b/drivers/i2c/i2c_connection.go index 178b9eab2..3f402a8d3 100644 --- a/drivers/i2c/i2c_connection.go +++ b/drivers/i2c/i2c_connection.go @@ -46,17 +46,17 @@ type i2cConnection struct { } // NewConnection creates and returns a new connection to a specific i2c device on a bus and address. -func NewConnection(bus gobot.I2cSystemDevicer, address int) (connection *i2cConnection) { +func NewConnection(bus gobot.I2cSystemDevicer, address int) *i2cConnection { return &i2cConnection{bus: bus, address: address} } // Read data from an i2c device. -func (c *i2cConnection) Read(data []byte) (read int, err error) { +func (c *i2cConnection) Read(data []byte) (int, error) { return c.bus.Read(c.address, data) } // Write data to an i2c device. -func (c *i2cConnection) Write(data []byte) (written int, err error) { +func (c *i2cConnection) Write(data []byte) (int, error) { return c.bus.Write(c.address, data) } @@ -96,17 +96,17 @@ func (c *i2cConnection) WriteByteData(reg uint8, val uint8) error { } // WriteWordData writes a word value to a register on the i2c device. -func (c *i2cConnection) WriteWordData(reg uint8, val uint16) (err error) { +func (c *i2cConnection) WriteWordData(reg uint8, val uint16) error { return c.bus.WriteWordData(c.address, reg, val) } // WriteBlockData writes a block of bytes to a register on the i2c device. -func (c *i2cConnection) WriteBlockData(reg uint8, b []byte) (err error) { +func (c *i2cConnection) WriteBlockData(reg uint8, b []byte) error { return c.bus.WriteBlockData(c.address, reg, b) } // WriteBytes writes a block of bytes to the current register on the i2c device. -func (c *i2cConnection) WriteBytes(b []byte) (err error) { +func (c *i2cConnection) WriteBytes(b []byte) error { return c.bus.WriteBytes(c.address, b) } diff --git a/drivers/i2c/i2c_connection_test.go b/drivers/i2c/i2c_connection_test.go index d4ee56cc6..fdce313d2 100644 --- a/drivers/i2c/i2c_connection_test.go +++ b/drivers/i2c/i2c_connection_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/system" ) @@ -21,6 +22,7 @@ func getSyscallFuncImpl( // bit 0: error on function query // bit 1: error on set address // bit 2: error on command + //nolint:nonamedreturns // is sufficient here return func(trap, a1, a2 uintptr, a3 unsafe.Pointer) (r1, r2 uintptr, err system.SyscallErrno) { // function query if (trap == system.Syscall_SYS_IOCTL) && (a2 == system.I2C_FUNCS) { diff --git a/drivers/i2c/i2c_driver.go b/drivers/i2c/i2c_driver.go index 88c26ab79..296b1c0c7 100644 --- a/drivers/i2c/i2c_driver.go +++ b/drivers/i2c/i2c_driver.go @@ -3,6 +3,7 @@ package i2c import ( "encoding/binary" "fmt" + "log" "strconv" "sync" @@ -81,7 +82,12 @@ func (d *Driver) SetName(name string) { // Connection returns the connection of the i2c device. func (d *Driver) Connection() gobot.Connection { - return d.connector.(gobot.Connection) + if conn, ok := d.connector.(gobot.Connection); ok { + return conn + } + + log.Printf("%s has no gobot connection\n", d.name) + return nil } // Start initializes the i2c device. diff --git a/drivers/i2c/i2c_driver_test.go b/drivers/i2c/i2c_driver_test.go index 9dec4cecd..28abcb388 100644 --- a/drivers/i2c/i2c_driver_test.go +++ b/drivers/i2c/i2c_driver_test.go @@ -5,6 +5,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/i2c/ina3221_driver_test.go b/drivers/i2c/ina3221_driver_test.go index 51cee46e9..7914dc8e8 100644 --- a/drivers/i2c/ina3221_driver_test.go +++ b/drivers/i2c/ina3221_driver_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/i2c/jhd1313m1_driver.go b/drivers/i2c/jhd1313m1_driver.go index 25649f77a..9d17818ec 100644 --- a/drivers/i2c/jhd1313m1_driver.go +++ b/drivers/i2c/jhd1313m1_driver.go @@ -2,6 +2,7 @@ package i2c import ( "fmt" + "log" "strconv" "time" @@ -93,7 +94,7 @@ type JHD1313M1Driver struct { // // i2c.WithBus(int): bus to use with this driver func NewJHD1313M1Driver(a Connector, options ...func(Config)) *JHD1313M1Driver { - j := &JHD1313M1Driver{ + d := &JHD1313M1Driver{ name: gobot.DefaultName("JHD1313M1"), connector: a, Config: NewConfig(), @@ -103,57 +104,63 @@ func NewJHD1313M1Driver(a Connector, options ...func(Config)) *JHD1313M1Driver { } for _, option := range options { - option(j) + option(d) } - j.AddCommand("SetRGB", func(params map[string]interface{}) interface{} { + d.AddCommand("SetRGB", func(params map[string]interface{}) interface{} { r, _ := strconv.Atoi(params["r"].(string)) g, _ := strconv.Atoi(params["g"].(string)) b, _ := strconv.Atoi(params["b"].(string)) - return j.SetRGB(r, g, b) + return d.SetRGB(r, g, b) }) - j.AddCommand("Clear", func(params map[string]interface{}) interface{} { - return j.Clear() + d.AddCommand("Clear", func(params map[string]interface{}) interface{} { + return d.Clear() }) - j.AddCommand("Home", func(params map[string]interface{}) interface{} { - return j.Home() + d.AddCommand("Home", func(params map[string]interface{}) interface{} { + return d.Home() }) - j.AddCommand("Write", func(params map[string]interface{}) interface{} { - msg := params["msg"].(string) - return j.Write(msg) + d.AddCommand("Write", func(params map[string]interface{}) interface{} { + msg := params["msg"].(string) //nolint:forcetypeassert // ok here + return d.Write(msg) }) - j.AddCommand("SetPosition", func(params map[string]interface{}) interface{} { + d.AddCommand("SetPosition", func(params map[string]interface{}) interface{} { pos, _ := strconv.Atoi(params["pos"].(string)) - return j.SetPosition(pos) + return d.SetPosition(pos) }) - j.AddCommand("Scroll", func(params map[string]interface{}) interface{} { + d.AddCommand("Scroll", func(params map[string]interface{}) interface{} { lr, _ := strconv.ParseBool(params["lr"].(string)) - return j.Scroll(lr) + return d.Scroll(lr) }) - return j + return d } // Name returns the name the JHD1313M1 Driver was given when created. -func (h *JHD1313M1Driver) Name() string { return h.name } +func (d *JHD1313M1Driver) Name() string { return d.name } // SetName sets the name for the JHD1313M1 Driver. -func (h *JHD1313M1Driver) SetName(n string) { h.name = n } +func (d *JHD1313M1Driver) SetName(n string) { d.name = n } // Connection returns the driver connection to the device. -func (h *JHD1313M1Driver) Connection() gobot.Connection { - return h.connector.(gobot.Connection) +func (d *JHD1313M1Driver) Connection() gobot.Connection { + if conn, ok := d.connector.(gobot.Connection); ok { + return conn + } + + log.Printf("%s has no gobot connection\n", d.name) + return nil } // Start starts the backlit and the screen and initializes the states. -func (h *JHD1313M1Driver) Start() (err error) { - bus := h.GetBusOrDefault(h.connector.DefaultI2cBus()) +func (d *JHD1313M1Driver) Start() error { + bus := d.GetBusOrDefault(d.connector.DefaultI2cBus()) - if h.lcdConnection, err = h.connector.GetI2cConnection(h.lcdAddress, bus); err != nil { + var err error + if d.lcdConnection, err = d.connector.GetI2cConnection(d.lcdAddress, bus); err != nil { return err } - if h.rgbConnection, err = h.connector.GetI2cConnection(h.rgbAddress, bus); err != nil { + if d.rgbConnection, err = d.connector.GetI2cConnection(d.rgbAddress, bus); err != nil { return err } @@ -166,90 +173,87 @@ func (h *JHD1313M1Driver) Start() (err error) { // page 45 figure 23 // Send function set command sequence init_payload := []byte{LCD_CMD, LCD_FUNCTIONSET | LCD_2LINE} - if _, err := h.lcdConnection.Write(init_payload); err != nil { + if _, err := d.lcdConnection.Write(init_payload); err != nil { return err } // wait more than 4.1ms time.Sleep(4500 * time.Microsecond) // second try - if _, err := h.lcdConnection.Write(init_payload); err != nil { + if _, err := d.lcdConnection.Write(init_payload); err != nil { return err } time.Sleep(150 * time.Microsecond) // third go - if _, err := h.lcdConnection.Write(init_payload); err != nil { + if _, err := d.lcdConnection.Write(init_payload); err != nil { return err } - if _, err := h.lcdConnection.Write([]byte{LCD_CMD, LCD_DISPLAYCONTROL | LCD_DISPLAYON}); err != nil { + if _, err := d.lcdConnection.Write([]byte{LCD_CMD, LCD_DISPLAYCONTROL | LCD_DISPLAYON}); err != nil { return err } time.Sleep(100 * time.Microsecond) - if err := h.Clear(); err != nil { + if err := d.Clear(); err != nil { return err } - if _, err := h.lcdConnection.Write([]byte{LCD_CMD, LCD_ENTRYMODESET | LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT}); err != nil { + if _, err := d.lcdConnection.Write([]byte{ + LCD_CMD, LCD_ENTRYMODESET | LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT, + }); err != nil { return err } - if err := h.setReg(0, 0); err != nil { + if err := d.setReg(0, 0); err != nil { return err } - if err := h.setReg(1, 0); err != nil { + if err := d.setReg(1, 0); err != nil { return err } - if err := h.setReg(0x08, 0xAA); err != nil { + if err := d.setReg(0x08, 0xAA); err != nil { return err } - if err := h.SetRGB(255, 255, 255); err != nil { - return err - } - - return nil + return d.SetRGB(255, 255, 255) } // SetRGB sets the Red Green Blue value of backlit. -func (h *JHD1313M1Driver) SetRGB(r, g, b int) error { - if err := h.setReg(REG_RED, r); err != nil { +func (d *JHD1313M1Driver) SetRGB(r, g, b int) error { + if err := d.setReg(REG_RED, r); err != nil { return err } - if err := h.setReg(REG_GREEN, g); err != nil { + if err := d.setReg(REG_GREEN, g); err != nil { return err } - return h.setReg(REG_BLUE, b) + return d.setReg(REG_BLUE, b) } // Clear clears the text on the lCD display. -func (h *JHD1313M1Driver) Clear() error { - err := h.command([]byte{LCD_CLEARDISPLAY}) - return err +func (d *JHD1313M1Driver) Clear() error { + return d.command([]byte{LCD_CLEARDISPLAY}) } // Home sets the cursor to the origin position on the display. -func (h *JHD1313M1Driver) Home() error { - err := h.command([]byte{LCD_RETURNHOME}) +func (d *JHD1313M1Driver) Home() error { + err := d.command([]byte{LCD_RETURNHOME}) // This wait fixes a race condition when calling home and clear back to back. time.Sleep(2 * time.Millisecond) return err } // Write displays the passed message on the screen. -func (h *JHD1313M1Driver) Write(message string) error { +func (d *JHD1313M1Driver) Write(message string) error { // This wait fixes an odd bug where the clear function doesn't always work properly. time.Sleep(1 * time.Millisecond) for _, val := range message { if val == '\n' { - if err := h.SetPosition(16); err != nil { + if err := d.SetPosition(16); err != nil { return err } continue } - if _, err := h.lcdConnection.Write([]byte{LCD_DATA, byte(val)}); err != nil { + if _, err := d.lcdConnection.Write([]byte{LCD_DATA, byte(val)}); err != nil { return err } } @@ -259,34 +263,33 @@ func (h *JHD1313M1Driver) Write(message string) error { // SetPosition sets the cursor and the data display to pos. // 0..15 are the positions in the first display line. // 16..32 are the positions in the second display line. -func (h *JHD1313M1Driver) SetPosition(pos int) (err error) { +func (d *JHD1313M1Driver) SetPosition(pos int) error { if pos < 0 || pos > 31 { - err = jhd1313m1ErrInvalidPosition - return + return jhd1313m1ErrInvalidPosition } offset := byte(pos) if pos >= 16 { offset -= 16 offset |= LCD_2NDLINEOFFSET } - err = h.command([]byte{LCD_SETDDRAMADDR | offset}) - return + + return d.command([]byte{LCD_SETDDRAMADDR | offset}) } // Scroll sets the scrolling direction for the display, either left to right, or // right to left. -func (h *JHD1313M1Driver) Scroll(lr bool) error { +func (d *JHD1313M1Driver) Scroll(lr bool) error { if lr { - _, err := h.lcdConnection.Write([]byte{LCD_CMD, LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVELEFT}) + _, err := d.lcdConnection.Write([]byte{LCD_CMD, LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVELEFT}) return err } - _, err := h.lcdConnection.Write([]byte{LCD_CMD, LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVERIGHT}) + _, err := d.lcdConnection.Write([]byte{LCD_CMD, LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVERIGHT}) return err } // Halt is a noop function. -func (h *JHD1313M1Driver) Halt() error { return nil } +func (d *JHD1313M1Driver) Halt() error { return nil } // SetCustomChar sets one of the 8 CGRAM locations with a custom character. // The custom character can be used by writing a byte of value 0 to 7. @@ -296,24 +299,24 @@ func (h *JHD1313M1Driver) Halt() error { return nil } // characters. // To use a custom character, write byte value of the custom character position as a string after // having setup the custom character. -func (h *JHD1313M1Driver) SetCustomChar(pos int, charMap [8]byte) error { +func (d *JHD1313M1Driver) SetCustomChar(pos int, charMap [8]byte) error { if pos > 7 { return fmt.Errorf("can't set a custom character at a position greater than 7") } location := uint8(pos) - if err := h.command([]byte{LCD_SETCGRAMADDR | (location << 3)}); err != nil { + if err := d.command([]byte{LCD_SETCGRAMADDR | (location << 3)}); err != nil { return err } - _, err := h.lcdConnection.Write(append([]byte{LCD_DATA}, charMap[:]...)) + _, err := d.lcdConnection.Write(append([]byte{LCD_DATA}, charMap[:]...)) return err } -func (h *JHD1313M1Driver) setReg(command int, data int) error { - _, err := h.rgbConnection.Write([]byte{byte(command), byte(data)}) +func (d *JHD1313M1Driver) setReg(command int, data int) error { + _, err := d.rgbConnection.Write([]byte{byte(command), byte(data)}) return err } -func (h *JHD1313M1Driver) command(buf []byte) error { - _, err := h.lcdConnection.Write(append([]byte{LCD_CMD}, buf...)) +func (d *JHD1313M1Driver) command(buf []byte) error { + _, err := d.lcdConnection.Write(append([]byte{LCD_CMD}, buf...)) return err } diff --git a/drivers/i2c/jhd1313m1_driver_test.go b/drivers/i2c/jhd1313m1_driver_test.go index 94ec4fbab..e6ffc273f 100644 --- a/drivers/i2c/jhd1313m1_driver_test.go +++ b/drivers/i2c/jhd1313m1_driver_test.go @@ -7,15 +7,16 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) var _ gobot.Driver = (*JHD1313M1Driver)(nil) // --------- HELPERS -func initTestJHD1313M1Driver() (driver *JHD1313M1Driver) { - driver, _ = initTestJHD1313M1DriverWithStubbedAdaptor() - return +func initTestJHD1313M1Driver() *JHD1313M1Driver { + d, _ := initTestJHD1313M1DriverWithStubbedAdaptor() + return d } func initTestJHD1313M1DriverWithStubbedAdaptor() (*JHD1313M1Driver, *i2cTestAdaptor) { diff --git a/drivers/i2c/l3gd20h_driver.go b/drivers/i2c/l3gd20h_driver.go index f88e91b10..c49001220 100644 --- a/drivers/i2c/l3gd20h_driver.go +++ b/drivers/i2c/l3gd20h_driver.go @@ -1,3 +1,4 @@ +//nolint:lll // ok here package i2c import ( @@ -111,6 +112,8 @@ func (d *L3GD20HDriver) FullScaleRange() (uint8, error) { } // XYZ returns the current change in degrees per second, for the 3 axis. +// +//nolint:nonamedreturns // is sufficient here func (d *L3GD20HDriver) XYZ() (x float32, y float32, z float32, err error) { d.mutex.Lock() defer d.mutex.Unlock() diff --git a/drivers/i2c/l3gd20h_driver_test.go b/drivers/i2c/l3gd20h_driver_test.go index caeccf94f..392ddb886 100644 --- a/drivers/i2c/l3gd20h_driver_test.go +++ b/drivers/i2c/l3gd20h_driver_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -14,9 +15,9 @@ import ( // and tests all implementations, so no further tests needed here for gobot.Driver interface var _ gobot.Driver = (*HMC6352Driver)(nil) -func initL3GD20HDriver() (driver *L3GD20HDriver) { - driver, _ = initL3GD20HWithStubbedAdaptor() - return +func initL3GD20HDriver() *L3GD20HDriver { + d, _ := initL3GD20HWithStubbedAdaptor() + return d } func initL3GD20HWithStubbedAdaptor() (*L3GD20HDriver, *i2cTestAdaptor) { @@ -214,8 +215,11 @@ func TestL3GD20HMeasurementError(t *testing.T) { } _ = d.Start() - _, _, _, err := d.XYZ() + x, y, z, err := d.XYZ() require.ErrorContains(t, err, "read error") + assert.InDelta(t, 0.0, x, 0.0) + assert.InDelta(t, 0.0, y, 0.0) + assert.InDelta(t, 0.0, z, 0.0) } func TestL3GD20HMeasurementWriteError(t *testing.T) { @@ -223,8 +227,11 @@ func TestL3GD20HMeasurementWriteError(t *testing.T) { a.i2cWriteImpl = func(b []byte) (int, error) { return 0, errors.New("write error") } - _, _, _, err := d.XYZ() + x, y, z, err := d.XYZ() require.ErrorContains(t, err, "write error") + assert.InDelta(t, 0.0, x, 0.0) + assert.InDelta(t, 0.0, y, 0.0) + assert.InDelta(t, 0.0, z, 0.0) } func TestL3GD20H_initialize(t *testing.T) { diff --git a/drivers/i2c/lidarlite_driver.go b/drivers/i2c/lidarlite_driver.go index 79f7d7d40..328d666a5 100644 --- a/drivers/i2c/lidarlite_driver.go +++ b/drivers/i2c/lidarlite_driver.go @@ -35,43 +35,41 @@ func NewLIDARLiteDriver(c Connector, options ...func(Config)) *LIDARLiteDriver { } // Distance returns the current distance in cm -func (h *LIDARLiteDriver) Distance() (distance int, err error) { - if _, err = h.connection.Write([]byte{0x00, 0x04}); err != nil { - return +func (h *LIDARLiteDriver) Distance() (int, error) { + if _, err := h.connection.Write([]byte{0x00, 0x04}); err != nil { + return 0, err } time.Sleep(20 * time.Millisecond) - if _, err = h.connection.Write([]byte{0x0F}); err != nil { - return + if _, err := h.connection.Write([]byte{0x0F}); err != nil { + return 0, err } upper := []byte{0} bytesRead, err := h.connection.Read(upper) if err != nil { - return + return 0, err } if bytesRead != 1 { - err = ErrNotEnoughBytes - return + return 0, ErrNotEnoughBytes } - if _, err = h.connection.Write([]byte{0x10}); err != nil { - return + if _, err := h.connection.Write([]byte{0x10}); err != nil { + return 0, err } lower := []byte{0} bytesRead, err = h.connection.Read(lower) if err != nil { - return + return 0, err } if bytesRead != 1 { - err = ErrNotEnoughBytes - return + return 0, ErrNotEnoughBytes } - distance = ((int(upper[0]) & 0xff) << 8) | (int(lower[0]) & 0xff) + distance := ((int(upper[0]) & 0xff) << 8) | (int(lower[0]) & 0xff) - return + return distance, nil } diff --git a/drivers/i2c/lidarlite_driver_test.go b/drivers/i2c/lidarlite_driver_test.go index 6b9a12376..8354b2648 100644 --- a/drivers/i2c/lidarlite_driver_test.go +++ b/drivers/i2c/lidarlite_driver_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -15,9 +16,9 @@ import ( // and tests all implementations, so no further tests needed here for gobot.Driver interface var _ gobot.Driver = (*LIDARLiteDriver)(nil) -func initTestLIDARLiteDriver() (driver *LIDARLiteDriver) { - driver, _ = initTestLIDARLiteDriverWithStubbedAdaptor() - return +func initTestLIDARLiteDriver() *LIDARLiteDriver { + d, _ := initTestLIDARLiteDriverWithStubbedAdaptor() + return d } func initTestLIDARLiteDriverWithStubbedAdaptor() (*LIDARLiteDriver, *i2cTestAdaptor) { diff --git a/drivers/i2c/mcp23017_driver.go b/drivers/i2c/mcp23017_driver.go index 4b8697859..d54abee76 100644 --- a/drivers/i2c/mcp23017_driver.go +++ b/drivers/i2c/mcp23017_driver.go @@ -20,13 +20,15 @@ type port struct { IPOL uint8 // input polarity register: 0=normal polarity / 1=inversed GPINTEN uint8 // interrupt on change control register: 0=disabled / 1=enabled DEFVAL uint8 // default compare register for interrupt on change - INTCON uint8 // interrupt control register: bit set to 0= use defval bit value to compare pin value/ bit set to 1= pin value compared to previous pin value - IOCON uint8 // configuration register - GPPU uint8 // pull-up resistor configuration register: 0=enabled / 1=disabled - INTF uint8 // interrupt flag register: 0=no interrupt / 1=pin caused interrupt - INTCAP uint8 // interrupt capture register, captures pin values during interrupt: 0=logic low / 1=logic high - GPIO uint8 // port register, reading from this register reads the port - OLAT uint8 // output latch register, write modifies the pins: 0=logic low / 1=logic high + // interrupt control register: bit set to 0= use defval bit value to compare pin value/ bit set to 1= pin value + // compared to previous pin value + INTCON uint8 + IOCON uint8 // configuration register + GPPU uint8 // pull-up resistor configuration register: 0=enabled / 1=disabled + INTF uint8 // interrupt flag register: 0=no interrupt / 1=pin caused interrupt + INTCAP uint8 // interrupt capture register, captures pin values during interrupt: 0=logic low / 1=logic high + GPIO uint8 // port register, reading from this register reads the port + OLAT uint8 // output latch register, write modifies the pins: 0=logic low / 1=logic high } // A bank is made up of PortA and PortB pins. @@ -89,6 +91,7 @@ func NewMCP23017Driver(c Connector, options ...func(Config)) *MCP23017Driver { option(d) } + //nolint:forcetypeassert // ok here d.AddCommand("WriteGPIO", func(params map[string]interface{}) interface{} { pin := params["pin"].(uint8) port := params["port"].(string) @@ -97,6 +100,7 @@ func NewMCP23017Driver(c Connector, options ...func(Config)) *MCP23017Driver { return map[string]interface{}{"err": err} }) + //nolint:forcetypeassert // ok here d.AddCommand("ReadGPIO", func(params map[string]interface{}) interface{} { pin := params["pin"].(uint8) port := params["port"].(string) @@ -228,16 +232,13 @@ func WithMCP23017AutoIODirOff(val uint8) func(Config) { // SetPinMode set pin mode of a given pin immediately, based on the value: // val = 0 output // val = 1 input -func (m *MCP23017Driver) SetPinMode(pin uint8, portStr string, val uint8) (err error) { +func (m *MCP23017Driver) SetPinMode(pin uint8, portStr string, val uint8) error { m.mutex.Lock() defer m.mutex.Unlock() selectedPort := m.getPort(portStr) // Set IODIR register bit for given pin to an output/input. - if err = m.write(selectedPort.IODIR, pin, bitState(val)); err != nil { - return - } - return + return m.write(selectedPort.IODIR, pin, bitState(val)) } // SetPullUp sets the pull up state of a given pin immediately, based on the value: @@ -254,7 +255,7 @@ func (m *MCP23017Driver) SetPullUp(pin uint8, portStr string, val uint8) error { // SetGPIOPolarity will change a given pin's polarity immediately, based on the value: // val = 1 opposite logic state of the input pin. // val = 0 same logic state of the input pin. -func (m *MCP23017Driver) SetGPIOPolarity(pin uint8, portStr string, val uint8) (err error) { +func (m *MCP23017Driver) SetGPIOPolarity(pin uint8, portStr string, val uint8) error { m.mutex.Lock() defer m.mutex.Unlock() @@ -263,7 +264,7 @@ func (m *MCP23017Driver) SetGPIOPolarity(pin uint8, portStr string, val uint8) ( } // WriteGPIO writes a value to a gpio pin (0-7) and a port (A or B). -func (m *MCP23017Driver) WriteGPIO(pin uint8, portStr string, val uint8) (err error) { +func (m *MCP23017Driver) WriteGPIO(pin uint8, portStr string, val uint8) error { m.mutex.Lock() defer m.mutex.Unlock() @@ -271,20 +272,16 @@ 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, pin, clear); err != nil { + if err := m.write(selectedPort.IODIR, pin, clear); err != nil { return err } } // write value to OLAT register bit - err = m.write(selectedPort.OLAT, pin, bitState(val)) - if err != nil { - return err - } - return nil + return m.write(selectedPort.OLAT, pin, bitState(val)) } // ReadGPIO reads a value from a given gpio pin (0-7) and a port (A or B). -func (m *MCP23017Driver) ReadGPIO(pin uint8, portStr string) (val uint8, err error) { +func (m *MCP23017Driver) ReadGPIO(pin uint8, portStr string) (uint8, error) { m.mutex.Lock() defer m.mutex.Unlock() @@ -292,11 +289,11 @@ 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, pin, set); err != nil { + if err := m.write(selectedPort.IODIR, pin, set); err != nil { return 0, err } } - val, err = m.read(selectedPort.GPIO) + val, err := m.read(selectedPort.GPIO) if err != nil { return val, err } @@ -307,19 +304,18 @@ func (m *MCP23017Driver) ReadGPIO(pin uint8, portStr string) (val uint8, err err return val, nil } -func (m *MCP23017Driver) initialize() (err error) { +func (m *MCP23017Driver) initialize() error { // Set IOCON register with MCP23017 configuration. ioconReg := m.getPort("A").IOCON // IOCON address is the same for Port A or B. ioconVal := m.mcpConf.getUint8Value() - if _, err := m.connection.Write([]uint8{ioconReg, ioconVal}); err != nil { - return err - } - return + + _, err := m.connection.Write([]uint8{ioconReg, ioconVal}) + return err } // write gets the value of the passed in register, and then sets the bit specified // by the pin to the given state. -func (m *MCP23017Driver) write(reg uint8, pin uint8, state bitState) (err error) { +func (m *MCP23017Driver) write(reg uint8, pin uint8, state bitState) error { valOrg, err := m.read(reg) if err != nil { return fmt.Errorf("MCP write-read: %v", err) @@ -337,22 +333,20 @@ func (m *MCP23017Driver) write(reg uint8, pin uint8, state bitState) (err error) log.Printf("write done: MCP forceRefresh: %t, address: 0x%X, register: 0x%X, name: %s, value: 0x%X\n", m.mcpBehav.forceRefresh, m.GetAddressOrDefault(mcp23017DefaultAddress), reg, m.getRegName(reg), val) } - if err = m.connection.WriteByteData(reg, val); err != nil { + if err := m.connection.WriteByteData(reg, val); err != nil { return fmt.Errorf("MCP write-WriteByteData(reg=%d,val=%d): %v", reg, val, err) } - } else { - if mcp23017Debug { - log.Printf("write skipped: MCP forceRefresh: %t, address: 0x%X, register: 0x%X, name: %s, value: 0x%X\n", - m.mcpBehav.forceRefresh, m.GetAddressOrDefault(mcp23017DefaultAddress), reg, m.getRegName(reg), val) - } + } else if mcp23017Debug { + log.Printf("write skipped: MCP forceRefresh: %t, address: 0x%X, register: 0x%X, name: %s, value: 0x%X\n", + m.mcpBehav.forceRefresh, m.GetAddressOrDefault(mcp23017DefaultAddress), reg, m.getRegName(reg), val) } return nil } // read get the data from a given register // it is mainly a wrapper to create additional debug messages, when activated -func (m *MCP23017Driver) read(reg uint8) (val uint8, err error) { - val, err = m.connection.ReadByteData(reg) +func (m *MCP23017Driver) read(reg uint8) (uint8, error) { + val, err := m.connection.ReadByteData(reg) if err != nil { return val, fmt.Errorf("MCP write-ReadByteData(reg=%d): %v", reg, err) } @@ -365,7 +359,7 @@ func (m *MCP23017Driver) read(reg uint8) (val uint8, err error) { // getPort return the port (A or B) given a string and the bank. // Port A is the default if an incorrect or no port is specified. -func (m *MCP23017Driver) getPort(portStr string) (selectedPort port) { +func (m *MCP23017Driver) getPort(portStr string) port { portStr = strings.ToUpper(portStr) switch { case portStr == "A": @@ -429,7 +423,13 @@ func (m *MCP23017Driver) getRegName(reg uint8) string { // mcp23017GetBank returns a bank's PortA and PortB registers given a bank number (0/1). func mcp23017GetBank(bnk uint8) bank { if bnk == 0 { - return bank{portA: port{0x00, 0x02, 0x04, 0x06, 0x08, 0x0A, 0x0C, 0x0E, 0x10, 0x12, 0x14}, portB: port{0x01, 0x03, 0x05, 0x07, 0x09, 0x0B, 0x0D, 0x0F, 0x11, 0x13, 0x15}} + return bank{ + portA: port{0x00, 0x02, 0x04, 0x06, 0x08, 0x0A, 0x0C, 0x0E, 0x10, 0x12, 0x14}, + portB: port{0x01, 0x03, 0x05, 0x07, 0x09, 0x0B, 0x0D, 0x0F, 0x11, 0x13, 0x15}, + } + } + return bank{ + portA: port{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A}, + portB: port{0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A}, } - return bank{portA: port{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A}, portB: port{0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A}} } diff --git a/drivers/i2c/mcp23017_driver_test.go b/drivers/i2c/mcp23017_driver_test.go index 544d2f897..5723c46d8 100644 --- a/drivers/i2c/mcp23017_driver_test.go +++ b/drivers/i2c/mcp23017_driver_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert // ok here package i2c import ( @@ -7,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -25,7 +27,7 @@ var pinPort = map[string]interface{}{ "port": "A", } -func initTestMCP23017(b uint8) (driver *MCP23017Driver) { +func initTestMCP23017(b uint8) *MCP23017Driver { // create the driver without starting it a := newI2cTestAdaptor() d := NewMCP23017Driver(a, WithMCP23017Bank(b)) diff --git a/drivers/i2c/mma7660_driver.go b/drivers/i2c/mma7660_driver.go index 8e9f5acd5..a82223adb 100644 --- a/drivers/i2c/mma7660_driver.go +++ b/drivers/i2c/mma7660_driver.go @@ -54,11 +54,15 @@ func NewMMA7660Driver(c Connector, options ...func(Config)) *MMA7660Driver { } // Acceleration returns the acceleration of the provided x, y, z +// +//nolint:nonamedreturns // is sufficient here func (d *MMA7660Driver) Acceleration(x, y, z float64) (ax, ay, az float64) { return x / 21.0, y / 21.0, z / 21.0 } // XYZ returns the raw x,y and z axis from the mma7660 +// +//nolint:nonamedreturns // is sufficient here func (d *MMA7660Driver) XYZ() (x float64, y float64, z float64, err error) { buf := []byte{0, 0, 0} bytesRead, err := d.connection.Read(buf) diff --git a/drivers/i2c/mma7660_driver_test.go b/drivers/i2c/mma7660_driver_test.go index a736f1ff8..7f2b05b6a 100644 --- a/drivers/i2c/mma7660_driver_test.go +++ b/drivers/i2c/mma7660_driver_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -90,8 +91,11 @@ func TestMMA7660XYZError(t *testing.T) { return 0, errors.New("read error") } - _, _, _, err := d.XYZ() + x, y, z, err := d.XYZ() require.ErrorContains(t, err, "read error") + assert.InDelta(t, 0.0, x, 0.0) + assert.InDelta(t, 0.0, y, 0.0) + assert.InDelta(t, 0.0, z, 0.0) } func TestMMA7660XYZNotReady(t *testing.T) { @@ -103,6 +107,9 @@ func TestMMA7660XYZNotReady(t *testing.T) { return buf.Len(), nil } - _, _, _, err := d.XYZ() + x, y, z, err := d.XYZ() assert.Equal(t, ErrNotReady, err) + assert.InDelta(t, 0.0, x, 0.0) + assert.InDelta(t, 0.0, y, 0.0) + assert.InDelta(t, 0.0, z, 0.0) } diff --git a/drivers/i2c/mpl115a2_driver.go b/drivers/i2c/mpl115a2_driver.go index cbe32206f..2d0250564 100644 --- a/drivers/i2c/mpl115a2_driver.go +++ b/drivers/i2c/mpl115a2_driver.go @@ -72,21 +72,21 @@ func NewMPL115A2Driver(c Connector, options ...func(Config)) *MPL115A2Driver { } // Pressure fetches the latest data from the MPL115A2, and returns the pressure in kPa -func (d *MPL115A2Driver) Pressure() (p float32, err error) { +func (d *MPL115A2Driver) Pressure() (float32, error) { d.mutex.Lock() defer d.mutex.Unlock() - p, _, err = d.getData() - return + p, _, err := d.getData() + return p, err } // Temperature fetches the latest data from the MPL115A2, and returns the temperature in °C -func (d *MPL115A2Driver) Temperature() (t float32, err error) { +func (d *MPL115A2Driver) Temperature() (float32, error) { d.mutex.Lock() defer d.mutex.Unlock() - _, t, err = d.getData() - return + _, t, err := d.getData() + return t, err } func (d *MPL115A2Driver) initialization() error { @@ -125,6 +125,8 @@ func (d *MPL115A2Driver) initialization() error { } // getData fetches the latest data from the MPL115A2 +// +//nolint:nonamedreturns // is sufficient here func (d *MPL115A2Driver) getData() (p, t float32, err error) { var temperature uint16 var pressure uint16 @@ -137,7 +139,7 @@ func (d *MPL115A2Driver) getData() (p, t float32, err error) { data := []byte{0, 0, 0, 0} if err = d.connection.ReadBlockData(mpl115A2Reg_PressureMSB, data); err != nil { - return + return 0, 0, err } buf := bytes.NewBuffer(data) @@ -155,5 +157,5 @@ func (d *MPL115A2Driver) getData() (p, t float32, err error) { p = (65.0/1023.0)*pressureComp + 50.0 t = ((float32(temperature) - 498.0) / -5.35) + 25.0 - return + return p, t, err } diff --git a/drivers/i2c/mpl115a2_driver_test.go b/drivers/i2c/mpl115a2_driver_test.go index bd0ad6422..7ae72b516 100644 --- a/drivers/i2c/mpl115a2_driver_test.go +++ b/drivers/i2c/mpl115a2_driver_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/i2c/mpu6050_driver_test.go b/drivers/i2c/mpu6050_driver_test.go index 15ba6e44a..8ba6a3668 100644 --- a/drivers/i2c/mpu6050_driver_test.go +++ b/drivers/i2c/mpu6050_driver_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/i2c/pca9501_driver.go b/drivers/i2c/pca9501_driver.go index 05677886b..daa7da583 100644 --- a/drivers/i2c/pca9501_driver.go +++ b/drivers/i2c/pca9501_driver.go @@ -37,6 +37,7 @@ func NewPCA9501Driver(a Connector, options ...func(Config)) *PCA9501Driver { p.afterStart = p.initialize // API commands + //nolint:forcetypeassert // ok here p.AddCommand("WriteGPIO", func(params map[string]interface{}) interface{} { pin := params["pin"].(uint8) val := params["val"].(uint8) @@ -44,12 +45,14 @@ func NewPCA9501Driver(a Connector, options ...func(Config)) *PCA9501Driver { return map[string]interface{}{"err": err} }) + //nolint:forcetypeassert // ok here p.AddCommand("ReadGPIO", func(params map[string]interface{}) interface{} { pin := params["pin"].(uint8) val, err := p.ReadGPIO(pin) return map[string]interface{}{"val": val, "err": err} }) + //nolint:forcetypeassert // ok here p.AddCommand("WriteEEPROM", func(params map[string]interface{}) interface{} { address := params["address"].(uint8) val := params["val"].(uint8) @@ -57,6 +60,7 @@ func NewPCA9501Driver(a Connector, options ...func(Config)) *PCA9501Driver { return map[string]interface{}{"err": err} }) + //nolint:forcetypeassert // ok here p.AddCommand("ReadEEPROM", func(params map[string]interface{}) interface{} { address := params["address"].(uint8) val, err := p.ReadEEPROM(address) @@ -149,10 +153,11 @@ func (p *PCA9501Driver) WriteEEPROM(address uint8, val uint8) error { return p.connectionMem.WriteByteData(address, val) } -func (p *PCA9501Driver) initialize() (err error) { +func (p *PCA9501Driver) initialize() error { // initialize the EEPROM connection bus := p.GetBusOrDefault(p.connector.DefaultI2cBus()) addressMem := p.GetAddressOrDefault(pca9501DefaultAddress) | 0x40 + var err error p.connectionMem, err = p.connector.GetI2cConnection(addressMem, bus) - return + return err } diff --git a/drivers/i2c/pca9501_driver_test.go b/drivers/i2c/pca9501_driver_test.go index 8f10608fb..d214f3538 100644 --- a/drivers/i2c/pca9501_driver_test.go +++ b/drivers/i2c/pca9501_driver_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert // ok here package i2c import ( @@ -7,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/i2c/pca953x_driver_test.go b/drivers/i2c/pca953x_driver_test.go index 5bee65857..a28e950e7 100644 --- a/drivers/i2c/pca953x_driver_test.go +++ b/drivers/i2c/pca953x_driver_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/i2c/pca9685_driver.go b/drivers/i2c/pca9685_driver.go index b8c1eddd2..24b6a7fdd 100644 --- a/drivers/i2c/pca9685_driver.go +++ b/drivers/i2c/pca9685_driver.go @@ -61,11 +61,13 @@ func NewPCA9685Driver(c Connector, options ...func(Config)) *PCA9685Driver { option(p) } + //nolint:forcetypeassert // ok here p.AddCommand("PwmWrite", func(params map[string]interface{}) interface{} { pin := params["pin"].(string) val, _ := strconv.Atoi(params["val"].(string)) return p.PwmWrite(pin, byte(val)) }) + //nolint:forcetypeassert // ok here p.AddCommand("ServoWrite", func(params map[string]interface{}) interface{} { pin := params["pin"].(string) val, _ := strconv.Atoi(params["val"].(string)) @@ -93,7 +95,7 @@ func NewPCA9685Driver(c Connector, options ...func(Config)) *PCA9685Driver { // off uint16 - the time to stop the pulse // // Most typically you set "on" to a zero value, and then set "off" to your desired duty. -func (p *PCA9685Driver) SetPWM(channel int, on uint16, off uint16) (err error) { +func (p *PCA9685Driver) SetPWM(channel int, on uint16, off uint16) error { if _, err := p.connection.Write([]byte{byte(pca9685Led0OnLReg + 4*channel), byte(on) & 0xFF}); err != nil { return err } @@ -106,11 +108,8 @@ func (p *PCA9685Driver) SetPWM(channel int, on uint16, off uint16) (err error) { return err } - if _, err := p.connection.Write([]byte{byte(pca9685Led0OffHReg + 4*channel), byte(off >> 8)}); err != nil { - return err - } - - return + _, err := p.connection.Write([]byte{byte(pca9685Led0OffHReg + 4*channel), byte(off >> 8)}) + return err } // SetAllPWM sets all channels to a pwm value from 0-4095. @@ -120,7 +119,7 @@ func (p *PCA9685Driver) SetPWM(channel int, on uint16, off uint16) (err error) { // off uint16 - the time to stop the pulse // // Most typically you set "on" to a zero value, and then set "off" to your desired duty. -func (p *PCA9685Driver) SetAllPWM(on uint16, off uint16) (err error) { +func (p *PCA9685Driver) SetAllPWM(on uint16, off uint16) error { if _, err := p.connection.Write([]byte{byte(pca9685AllLedOnLReg), byte(on) & 0xFF}); err != nil { return err } @@ -133,11 +132,8 @@ func (p *PCA9685Driver) SetAllPWM(on uint16, off uint16) (err error) { return err } - if _, err := p.connection.Write([]byte{byte(pca9685AllLedOffHReg), byte(off >> 8)}); err != nil { - return err - } - - return + _, err := p.connection.Write([]byte{byte(pca9685AllLedOffHReg), byte(off >> 8)}) + return err } // SetPWMFreq sets the PWM frequency in Hz between 24Hz and 1526Hz, the default is 200Hz. @@ -180,20 +176,17 @@ func (p *PCA9685Driver) SetPWMFreq(freq float32) error { // initiate a restart restartMode := oldmode | pca9685Mode1RegRestartBit - if _, err := p.connection.Write([]byte{byte(pca9685Mode1Reg), restartMode}); err != nil { - return err - } - - return nil + _, err = p.connection.Write([]byte{byte(pca9685Mode1Reg), restartMode}) + return err } // PwmWrite writes a PWM signal to the specified channel aka "pin". // Value values are from 0-255, to conform to the PwmWriter interface. // If you need finer control, please look at SetPWM(). -func (p *PCA9685Driver) PwmWrite(pin string, val byte) (err error) { +func (p *PCA9685Driver) PwmWrite(pin string, val byte) error { i, err := strconv.Atoi(pin) if err != nil { - return + return err } v := gobot.ToScale(gobot.FromScale(float64(val), 0, 255), 0, 4095) return p.SetPWM(i, 0, uint16(v)) @@ -202,10 +195,10 @@ func (p *PCA9685Driver) PwmWrite(pin string, val byte) (err error) { // ServoWrite writes a servo signal to the specified channel aka "pin". // Valid values are from 0-180, to conform to the ServoWriter interface. // If you need finer control, please look at SetPWM(). -func (p *PCA9685Driver) ServoWrite(pin string, val byte) (err error) { +func (p *PCA9685Driver) ServoWrite(pin string, val byte) error { i, err := strconv.Atoi(pin) if err != nil { - return + return err } v := gobot.ToScale(gobot.FromScale(float64(val), 0, 180), 200, 500) return p.SetPWM(i, 0, uint16(v)) diff --git a/drivers/i2c/pca9685_driver_test.go b/drivers/i2c/pca9685_driver_test.go index 4880ec140..9363f02b8 100644 --- a/drivers/i2c/pca9685_driver_test.go +++ b/drivers/i2c/pca9685_driver_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/gpio" ) diff --git a/drivers/i2c/pcf8583_driver.go b/drivers/i2c/pcf8583_driver.go index 2db6821b2..70883b72a 100644 --- a/drivers/i2c/pcf8583_driver.go +++ b/drivers/i2c/pcf8583_driver.go @@ -43,7 +43,7 @@ const ( pcf8583CtrlStopCounting PCF8583Control = 0x80 // 0: count, 1: stop counting, reset divider ) -// PCF8583Driver is a Gobot Driver for the PCF8583 clock and calendar chip & 240 x 8-bit bit RAM with 1 address program pin. +// PCF8583Driver is a driver for the PCF8583 clock and calendar chip & 240 x 8-bit bit RAM with 1 address program pin. // please refer to data sheet: https://www.nxp.com/docs/en/data-sheet/PCF8583.pdf // // 0 1 0 1 0 0 0 A0|rd @@ -81,35 +81,34 @@ func NewPCF8583Driver(c Connector, options ...func(Config)) *PCF8583Driver { } // API commands + //nolint:forcetypeassert // ok here d.AddCommand("WriteTime", func(params map[string]interface{}) interface{} { val := params["val"].(time.Time) err := d.WriteTime(val) return map[string]interface{}{"err": err} }) - d.AddCommand("ReadTime", func(params map[string]interface{}) interface{} { val, err := d.ReadTime() return map[string]interface{}{"val": val, "err": err} }) - + //nolint:forcetypeassert // ok here d.AddCommand("WriteCounter", func(params map[string]interface{}) interface{} { val := params["val"].(int32) err := d.WriteCounter(val) return map[string]interface{}{"err": err} }) - d.AddCommand("ReadCounter", func(params map[string]interface{}) interface{} { val, err := d.ReadCounter() return map[string]interface{}{"val": val, "err": err} }) - + //nolint:forcetypeassert // ok here d.AddCommand("WriteRAM", func(params map[string]interface{}) interface{} { address := params["address"].(uint8) val := params["val"].(uint8) err := d.WriteRAM(address, val) return map[string]interface{}{"err": err} }) - + //nolint:forcetypeassert // ok here d.AddCommand("ReadRAM", func(params map[string]interface{}) interface{} { address := params["address"].(uint8) val, err := d.ReadRAM(address) @@ -152,12 +151,15 @@ func (d *PCF8583Driver) WriteTime(val time.Time) error { err = d.connection.WriteBlockData(uint8(pcf8583Reg_CTRL), []byte{ ctrlRegVal | uint8(pcf8583CtrlStopCounting), - pcf8583encodeBcd(uint8(val.Nanosecond() / 1000000 / 10)), // sub seconds in 1/10th seconds + // sub seconds in 1/10th seconds + pcf8583encodeBcd(uint8(val.Nanosecond() / 1000000 / 10)), pcf8583encodeBcd(uint8(val.Second())), pcf8583encodeBcd(uint8(val.Minute())), pcf8583encodeBcd(uint8(val.Hour())), - pcf8583encodeBcd(uint8(day)), // year, date (we keep the year counter zero and set the offset) - uint8(val.Weekday())<<5 | pcf8583encodeBcd(uint8(month)), // month, weekday (not BCD): Sunday = 0, Monday = 1 ... + // year, date (we keep the year counter zero and set the offset) + pcf8583encodeBcd(uint8(day)), + // month, weekday (not BCD): Sunday = 0, Monday = 1 ... + uint8(val.Weekday())<<5 | pcf8583encodeBcd(uint8(month)), }) if err != nil { return err @@ -167,7 +169,7 @@ func (d *PCF8583Driver) WriteTime(val time.Time) error { } // ReadTime reads the clock and returns the value -func (d *PCF8583Driver) ReadTime() (val time.Time, err error) { +func (d *PCF8583Driver) ReadTime() (time.Time, error) { d.mutex.Lock() defer d.mutex.Unlock() @@ -175,20 +177,20 @@ func (d *PCF8583Driver) ReadTime() (val time.Time, err error) { // is not needed when reading with auto increment ctrlRegVal, err := d.connection.ReadByteData(uint8(pcf8583Reg_CTRL)) if err != nil { - return + return time.Time{}, err } if !PCF8583Control(ctrlRegVal).isClockMode() { - return val, fmt.Errorf("%s: can't read time because the device is in wrong mode 0x%02x", d.name, ctrlRegVal) + return time.Time{}, fmt.Errorf("%s: can't read time because the device is in wrong mode 0x%02x", d.name, ctrlRegVal) } // auto increment feature is used clockDataSize := 6 data := make([]byte, clockDataSize) read, err := d.connection.Read(data) if err != nil { - return + return time.Time{}, err } if read != clockDataSize { - return val, fmt.Errorf("%s: %d bytes read, but %d expected", d.name, read, clockDataSize) + return time.Time{}, fmt.Errorf("%s: %d bytes read, but %d expected", d.name, read, clockDataSize) } nanos := int(pcf8583decodeBcd(data[0])) * 1000000 * 10 // sub seconds in 1/10th seconds seconds := int(pcf8583decodeBcd(data[1])) @@ -231,7 +233,7 @@ func (d *PCF8583Driver) WriteCounter(val int32) error { } // ReadCounter reads the counter registers -func (d *PCF8583Driver) ReadCounter() (val int32, err error) { +func (d *PCF8583Driver) ReadCounter() (int32, error) { d.mutex.Lock() defer d.mutex.Unlock() @@ -239,20 +241,20 @@ func (d *PCF8583Driver) ReadCounter() (val int32, err error) { // is not needed when reading with auto increment ctrlRegVal, err := d.connection.ReadByteData(uint8(pcf8583Reg_CTRL)) if err != nil { - return + return 0, err } if !PCF8583Control(ctrlRegVal).isCounterMode() { - return val, fmt.Errorf("%s: can't read counter because the device is in wrong mode 0x%02x", d.name, ctrlRegVal) + return 0, fmt.Errorf("%s: can't read counter because the device is in wrong mode 0x%02x", d.name, ctrlRegVal) } // auto increment feature is used counterDataSize := 3 data := make([]byte, counterDataSize) read, err := d.connection.Read(data) if err != nil { - return + return 0, err } if read != counterDataSize { - return val, fmt.Errorf("%s: %d bytes read, but %d expected", d.name, read, counterDataSize) + return 0, fmt.Errorf("%s: %d bytes read, but %d expected", d.name, read, counterDataSize) } return int32(pcf8583decodeBcd(data[0])) + int32(pcf8583decodeBcd(data[1]))*100 + @@ -272,13 +274,13 @@ func (d *PCF8583Driver) WriteRAM(address uint8, val uint8) error { } // ReadRAM reads a value from a given address (0x00-0xFF) -func (d *PCF8583Driver) ReadRAM(address uint8) (val uint8, err error) { +func (d *PCF8583Driver) ReadRAM(address uint8) (uint8, error) { d.mutex.Lock() defer d.mutex.Unlock() realAddress := uint16(address) + uint16(d.ramOffset) if realAddress > 0xFF { - return val, fmt.Errorf("%s: RAM address overflow %d", d.name, realAddress) + return 0, fmt.Errorf("%s: RAM address overflow %d", d.name, realAddress) } return d.connection.ReadByteData(uint8(realAddress)) } diff --git a/drivers/i2c/pcf8583_driver_test.go b/drivers/i2c/pcf8583_driver_test.go index 9fd6355b2..f91cd3e0c 100644 --- a/drivers/i2c/pcf8583_driver_test.go +++ b/drivers/i2c/pcf8583_driver_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert // ok here package i2c import ( @@ -7,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -248,7 +250,7 @@ func TestPCF8583WriteTimeNoTimeModeFails(t *testing.T) { err := d.WriteTime(time.Now()) // assert require.Error(t, err) - assert.Contains(t, err.Error(), "wrong mode 0x30") + require.ErrorContains(t, err, "wrong mode 0x30") assert.Len(t, a.written, 1) assert.Equal(t, uint8(pcf8583Reg_CTRL), a.written[0]) assert.Equal(t, 1, numCallsRead) @@ -320,7 +322,7 @@ func TestPCF8583ReadTimeNoTimeModeFails(t *testing.T) { got, err := d.ReadTime() // assert require.Error(t, err) - assert.Contains(t, err.Error(), "wrong mode 0x20") + require.ErrorContains(t, err, "wrong mode 0x20") assert.Equal(t, time.Time{}, got) assert.Len(t, a.written, 1) assert.Equal(t, uint8(pcf8583Reg_CTRL), a.written[0]) @@ -391,7 +393,7 @@ func TestPCF8583WriteCounterNoCounterModeFails(t *testing.T) { err := d.WriteCounter(123) // assert require.Error(t, err) - assert.Contains(t, err.Error(), "wrong mode 0x10") + require.ErrorContains(t, err, "wrong mode 0x10") assert.Len(t, a.written, 1) assert.Equal(t, uint8(pcf8583Reg_CTRL), a.written[0]) assert.Equal(t, 1, numCallsRead) @@ -458,7 +460,7 @@ func TestPCF8583ReadCounterNoCounterModeFails(t *testing.T) { got, err := d.ReadCounter() // assert require.Error(t, err) - assert.Contains(t, err.Error(), "wrong mode 0x30") + require.ErrorContains(t, err, "wrong mode 0x30") assert.Equal(t, int32(0), got) assert.Len(t, a.written, 1) assert.Equal(t, uint8(pcf8583Reg_CTRL), a.written[0]) @@ -495,7 +497,7 @@ func TestPCF8583WriteRamAddressOverflowFails(t *testing.T) { err := d.WriteRAM(uint8(0xF0), 15) // assert require.Error(t, err) - assert.Contains(t, err.Error(), "overflow 256") + require.ErrorContains(t, err, "overflow 256") assert.Empty(t, a.written) } @@ -547,7 +549,7 @@ func TestPCF8583ReadRamAddressOverflowFails(t *testing.T) { got, err := d.ReadRAM(uint8(0xF0)) // assert require.Error(t, err) - assert.Contains(t, err.Error(), "overflow 256") + require.ErrorContains(t, err, "overflow 256") assert.Equal(t, uint8(0), got) assert.Empty(t, a.written) assert.Equal(t, 0, numCallsRead) diff --git a/drivers/i2c/pcf8591_driver.go b/drivers/i2c/pcf8591_driver.go index e686429ad..8946cc03b 100644 --- a/drivers/i2c/pcf8591_driver.go +++ b/drivers/i2c/pcf8591_driver.go @@ -191,7 +191,7 @@ func WithPCF8591ForceRefresh(val uint8) func(Config) { // 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) { +func (p *PCF8591Driver) AnalogRead(description string) (int, error) { p.mutex.Lock() defer p.mutex.Unlock() @@ -232,7 +232,7 @@ func (p *PCF8591Driver) AnalogRead(description string) (value int, err error) { } // prepare return value - value = int(uval) + value := int(uval) if mc.pcf8591IsDiff() { if uval > 127 { // first bit is set, means negative @@ -240,13 +240,13 @@ func (p *PCF8591Driver) AnalogRead(description string) (value int, err error) { } } - return value, err + return value, nil } // AnalogWrite writes the given value to the analog output (DAC) // Vlsb = (Vref-Vagnd)/256, Vaout = Vagnd+Vlsb*value // implements the aio.AnalogWriter interface, pin is unused here -func (p *PCF8591Driver) AnalogWrite(pin string, value int) (err error) { +func (p *PCF8591Driver) AnalogWrite(pin string, value int) error { p.mutex.Lock() defer p.mutex.Unlock() @@ -260,8 +260,7 @@ func (p *PCF8591Driver) AnalogWrite(pin string, value int) (err error) { } ctrlByte := p.lastCtrlByte | byte(pcf8591_ANAON) - err = p.connection.WriteByteData(ctrlByte, byteVal) - if err != nil { + if err := p.connection.WriteByteData(ctrlByte, byteVal); err != nil { return err } @@ -281,8 +280,8 @@ func (p *PCF8591Driver) AnalogOutputState(state bool) error { return p.analogOutputState(state) } -// PCF8591ParseModeChan is used to get a working combination between mode (single, mixed, 2 differential, 3 differential) -// and the related channel to read from, parsed from the given description string. +// PCF8591ParseModeChan is used to get a working combination between mode (single, mixed, 2 differential, +// 3 differential) and the related channel to read from, parsed from the given description string. func PCF8591ParseModeChan(description string) (*pcf8591ModeChan, error) { mc, ok := pcf8591ModeMap[description] if !ok { @@ -303,10 +302,8 @@ func (p *PCF8591Driver) writeCtrlByte(ctrlByte uint8, forceRefresh bool) error { return err } p.lastCtrlByte = ctrlByte - } else { - if pcf8591Debug { - log.Printf("write skipped because control byte unchanged: 0x%X\n", ctrlByte) - } + } else if pcf8591Debug { + log.Printf("write skipped because control byte unchanged: 0x%X\n", ctrlByte) } return nil } @@ -343,7 +340,7 @@ func (p *PCF8591Driver) initialize() error { return p.analogOutputState(false) } -func (p *PCF8591Driver) shutdown() (err error) { +func (p *PCF8591Driver) shutdown() error { return p.analogOutputState(false) } diff --git a/drivers/i2c/pcf8591_driver_test.go b/drivers/i2c/pcf8591_driver_test.go index 0936631b4..a0eedf1ab 100644 --- a/drivers/i2c/pcf8591_driver_test.go +++ b/drivers/i2c/pcf8591_driver_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/i2c/sht2x_driver.go b/drivers/i2c/sht2x_driver.go index abbf376b6..f4c24f056 100644 --- a/drivers/i2c/sht2x_driver.go +++ b/drivers/i2c/sht2x_driver.go @@ -110,59 +110,59 @@ func NewSHT2xDriver(c Connector, options ...func(Config)) *SHT2xDriver { func (d *SHT2xDriver) Accuracy() byte { return d.accuracy } // SetAccuracy sets the accuracy of the sampling -func (d *SHT2xDriver) SetAccuracy(acc byte) (err error) { +func (d *SHT2xDriver) SetAccuracy(acc byte) error { d.accuracy = acc if d.connection != nil { - err = d.sendAccuracy() + return d.sendAccuracy() } - return + return nil } // Reset does a software reset of the device -func (d *SHT2xDriver) Reset() (err error) { - if err = d.connection.WriteByte(SHT2xSoftReset); err != nil { - return +func (d *SHT2xDriver) Reset() error { + if err := d.connection.WriteByte(SHT2xSoftReset); err != nil { + return err } time.Sleep(15 * time.Millisecond) // 15ms delay (from the datasheet 5.5) - return + return nil } // Temperature returns the current temperature, in celsius degrees. -func (d *SHT2xDriver) Temperature() (temp float32, err error) { - var rawT uint16 - if rawT, err = d.readSensor(SHT2xTriggerTempMeasureNohold); err != nil { - return +func (d *SHT2xDriver) Temperature() (float32, error) { + rawT, err := d.readSensor(SHT2xTriggerTempMeasureNohold) + if err != nil { + return 0, err } // From the datasheet 6.2: // T[C] = -46.85 + 175.72 * St / 2^16 - temp = -46.85 + 175.72/65536.0*float32(rawT) + temp := -46.85 + 175.72/65536.0*float32(rawT) - return + return temp, nil } // Humidity returns the current humidity in percentage of relative humidity -func (d *SHT2xDriver) Humidity() (humidity float32, err error) { - var rawH uint16 - if rawH, err = d.readSensor(SHT2xTriggerHumdMeasureNohold); err != nil { - return +func (d *SHT2xDriver) Humidity() (float32, error) { + rawH, err := d.readSensor(SHT2xTriggerHumdMeasureNohold) + if err != nil { + return 0, err } // From the datasheet 6.1: // RH = -6 + 125 * Srh / 2^16 - humidity = -6.0 + 125.0/65536.0*float32(rawH) + humidity := -6.0 + 125.0/65536.0*float32(rawH) - return + return humidity, nil } // sendCommandDelayGetResponse is a helper function to reduce duplicated code -func (d *SHT2xDriver) readSensor(cmd byte) (read uint16, err error) { - if err = d.connection.WriteByte(cmd); err != nil { - return +func (d *SHT2xDriver) readSensor(cmd byte) (uint16, error) { + if err := d.connection.WriteByte(cmd); err != nil { + return 0, err } // Hang out while measurement is taken. 85ms max, page 9 of datasheet. @@ -172,16 +172,14 @@ func (d *SHT2xDriver) readSensor(cmd byte) (read uint16, err error) { buf := make([]byte, 3) counter := 0 for { - var got int - got, err = d.connection.Read(buf) + got, err := d.connection.Read(buf) counter++ if counter > 50 { - return + return 0, err } if err == nil { if got != 3 { - err = ErrNotEnoughBytes - return + return 0, ErrNotEnoughBytes } break } @@ -191,13 +189,12 @@ func (d *SHT2xDriver) readSensor(cmd byte) (read uint16, err error) { // Store the result crc := crc8.Checksum(buf[0:2], d.crcTable) if buf[2] != crc { - err = errors.New("Invalid crc") - return + return 0, errors.New("Invalid crc") } - read = uint16(buf[0])<<8 | uint16(buf[1]) + read := uint16(buf[0])<<8 | uint16(buf[1]) read &= 0xfffc // clear two low bits (status bits) - return + return read, nil } func (d *SHT2xDriver) initialize() error { @@ -205,11 +202,7 @@ func (d *SHT2xDriver) initialize() error { return err } - if err := d.sendAccuracy(); err != nil { - return err - } - - return nil + return d.sendAccuracy() } func (d *SHT2xDriver) sendAccuracy() error { @@ -231,9 +224,6 @@ func (d *SHT2xDriver) sendAccuracy() error { return err } - if _, err := d.connection.ReadByte(); err != nil { - return err - } - - return nil + _, err = d.connection.ReadByte() + return err } diff --git a/drivers/i2c/sht2x_driver_test.go b/drivers/i2c/sht2x_driver_test.go index 9ae532b02..5c870c63f 100644 --- a/drivers/i2c/sht2x_driver_test.go +++ b/drivers/i2c/sht2x_driver_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -87,11 +88,12 @@ func TestSHT2xAccuracy(t *testing.T) { d, a := initTestSHT2xDriverWithStubbedAdaptor() a.i2cReadImpl = func(b []byte) (int, error) { buf := new(bytes.Buffer) - if a.written[len(a.written)-1] == SHT2xReadUserReg { + switch { + case a.written[len(a.written)-1] == SHT2xReadUserReg: buf.Write([]byte{0x3a}) - } else if a.written[len(a.written)-2] == SHT2xWriteUserReg { + case a.written[len(a.written)-2] == SHT2xWriteUserReg: buf.Write([]byte{a.written[len(a.written)-1]}) - } else { + default: return 0, nil } copy(b, buf.Bytes()) diff --git a/drivers/i2c/sht3x_driver.go b/drivers/i2c/sht3x_driver.go index c9d16220a..22314f26c 100644 --- a/drivers/i2c/sht3x_driver.go +++ b/drivers/i2c/sht3x_driver.go @@ -91,7 +91,7 @@ func NewSHT3xDriver(c Connector, options ...func(Config)) *SHT3xDriver { func (s *SHT3xDriver) Accuracy() byte { return s.accuracy } // SetAccuracy sets the accuracy of the sampling -func (s *SHT3xDriver) SetAccuracy(a byte) (err error) { +func (s *SHT3xDriver) SetAccuracy(a byte) error { switch a { case SHT3xAccuracyLow: s.delay = 5 * time.Millisecond // Actual max is 4, wait 1 ms longer @@ -100,47 +100,53 @@ func (s *SHT3xDriver) SetAccuracy(a byte) (err error) { case SHT3xAccuracyHigh: s.delay = 16 * time.Millisecond // Actual max is 15, wait 1 ms longer default: - err = ErrInvalidAccuracy - return + return ErrInvalidAccuracy } s.accuracy = a - return + return nil } // SerialNumber returns the serial number of the chip -func (s *SHT3xDriver) SerialNumber() (sn uint32, err error) { +func (s *SHT3xDriver) SerialNumber() (uint32, error) { ret, err := s.sendCommandDelayGetResponse([]byte{0x37, 0x80}, nil, 2) - if nil == err { - sn = (uint32(ret[0]) << 16) | uint32(ret[1]) + if err != nil { + return 0, err } - return + sn := (uint32(ret[0]) << 16) | uint32(ret[1]) + + return sn, nil } // Heater returns true if the heater is enabled -func (s *SHT3xDriver) Heater() (status bool, err error) { +func (s *SHT3xDriver) Heater() (bool, error) { sr, err := s.getStatusRegister() - if err == nil { - if (1 << 13) == (sr & (1 << 13)) { - status = true - } + if err != nil { + return false, err } - return + + if (1 << 13) == (sr & (1 << 13)) { + return true, nil + } + + return false, nil } // SetHeater enables or disables the heater on the device -func (s *SHT3xDriver) SetHeater(enabled bool) (err error) { +func (s *SHT3xDriver) SetHeater(enabled bool) error { out := []byte{0x30, 0x66} if enabled { out[1] = 0x6d } - _, err = s.connection.Write(out) - return + _, err := s.connection.Write(out) + return err } // Sample returns the temperature in celsius and relative humidity for one sample +// +//nolint:nonamedreturns // is sufficient here func (s *SHT3xDriver) Sample() (temp float32, rh float32, err error) { ret, err := s.sendCommandDelayGetResponse([]byte{0x24, s.accuracy}, &s.delay, 2) if nil != err { @@ -170,18 +176,19 @@ func (s *SHT3xDriver) Sample() (temp float32, rh float32, err error) { } // getStatusRegister returns the device status register -func (s *SHT3xDriver) getStatusRegister() (status uint16, err error) { +func (s *SHT3xDriver) getStatusRegister() (uint16, error) { ret, err := s.sendCommandDelayGetResponse([]byte{0xf3, 0x2d}, nil, 1) - if nil == err { - status = ret[0] + if err != nil { + return 0, err } - return + + return ret[0], nil } // sendCommandDelayGetResponse is a helper function to reduce duplicated code -func (s *SHT3xDriver) sendCommandDelayGetResponse(send []byte, delay *time.Duration, expect int) (read []uint16, err error) { - if _, err = s.connection.Write(send); err != nil { - return +func (s *SHT3xDriver) sendCommandDelayGetResponse(send []byte, delay *time.Duration, expect int) ([]uint16, error) { + if _, err := s.connection.Write(send); err != nil { + return []uint16{}, err } if nil != delay { @@ -191,22 +198,20 @@ func (s *SHT3xDriver) sendCommandDelayGetResponse(send []byte, delay *time.Durat buf := make([]byte, 3*expect) got, err := s.connection.Read(buf) if err != nil { - return + return []uint16{}, err } if got != (3 * expect) { - err = ErrNotEnoughBytes - return + return []uint16{}, ErrNotEnoughBytes } - read = make([]uint16, expect) + read := make([]uint16, expect) for i := 0; i < expect; i++ { crc := crc8.Checksum(buf[i*3:i*3+2], s.crcTable) if buf[i*3+2] != crc { - err = ErrInvalidCrc - return + return []uint16{}, ErrInvalidCrc } read[i] = uint16(buf[i*3])<<8 | uint16(buf[i*3+1]) } - return + return read, nil } diff --git a/drivers/i2c/sht3x_driver_test.go b/drivers/i2c/sht3x_driver_test.go index 13611382c..9174cd544 100644 --- a/drivers/i2c/sht3x_driver_test.go +++ b/drivers/i2c/sht3x_driver_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/i2c/ssd1306_driver.go b/drivers/i2c/ssd1306_driver.go index 9a8e92944..f7a674d05 100644 --- a/drivers/i2c/ssd1306_driver.go +++ b/drivers/i2c/ssd1306_driver.go @@ -234,11 +234,13 @@ func NewSSD1306Driver(c Connector, options ...func(Config)) *SSD1306Driver { s.Clear() return map[string]interface{}{} }) + //nolint:forcetypeassert // ok here s.AddCommand("SetContrast", func(params map[string]interface{}) interface{} { contrast := params["contrast"].(byte) err := s.SetContrast(contrast) return map[string]interface{}{"err": err} }) + //nolint:forcetypeassert // ok here s.AddCommand("Set", func(params map[string]interface{}) interface{} { x := params["x"].(int) y := params["y"].(int) @@ -280,31 +282,29 @@ func WithSSD1306ExternalVCC(val bool) func(Config) { } // Init initializes the ssd1306 display. -func (s *SSD1306Driver) Init() (err error) { +func (s *SSD1306Driver) Init() error { // turn off screen - if err = s.Off(); err != nil { + if err := s.Off(); err != nil { return err } // run through initialization commands - if err = s.commands(s.initSequence.GetSequence()); err != nil { + if err := s.commands(s.initSequence.GetSequence()); err != nil { return err } - if err = s.commands([]byte{ssd1306ColumnAddr, 0, byte(s.buffer.width) - 1}); err != nil { + if err := s.commands([]byte{ssd1306ColumnAddr, 0, byte(s.buffer.width) - 1}); err != nil { return err } - if err = s.commands([]byte{ssd1306PageAddr, 0, (byte(s.buffer.height / s.pageSize)) - 1}); err != nil { - return err - } - return nil + + return s.commands([]byte{ssd1306PageAddr, 0, (byte(s.buffer.height / s.pageSize)) - 1}) } // On turns on the display. -func (s *SSD1306Driver) On() (err error) { +func (s *SSD1306Driver) On() error { return s.command(ssd1306SetDisplayOn) } // Off turns off the display. -func (s *SSD1306Driver) Off() (err error) { +func (s *SSD1306Driver) Off() error { return s.command(ssd1306SetDisplayOff) } @@ -319,31 +319,28 @@ func (s *SSD1306Driver) Set(x, y, c int) { } // Reset clears display. -func (s *SSD1306Driver) Reset() (err error) { - if err = s.Off(); err != nil { +func (s *SSD1306Driver) Reset() error { + if err := s.Off(); err != nil { return err } s.Clear() - if err = s.On(); err != nil { - return err - } - return nil + + return s.On() } // SetContrast sets the display contrast. -func (s *SSD1306Driver) SetContrast(contrast byte) (err error) { - err = s.commands([]byte{ssd1306SetContrast, contrast}) - return +func (s *SSD1306Driver) SetContrast(contrast byte) error { + return s.commands([]byte{ssd1306SetContrast, contrast}) } // Display sends the memory buffer to the display. -func (s *SSD1306Driver) Display() (err error) { - _, err = s.connection.Write(append([]byte{0x40}, s.buffer.buffer...)) +func (s *SSD1306Driver) Display() error { + _, err := s.connection.Write(append([]byte{0x40}, s.buffer.buffer...)) return err } // ShowImage takes a standard Go image and displays it in monochrome. -func (s *SSD1306Driver) ShowImage(img image.Image) (err error) { +func (s *SSD1306Driver) ShowImage(img image.Image) error { if img.Bounds().Dx() != s.displayWidth || img.Bounds().Dy() != s.displayHeight { return fmt.Errorf("image must match display width and height: %dx%d", s.displayWidth, s.displayHeight) } @@ -360,22 +357,22 @@ func (s *SSD1306Driver) ShowImage(img image.Image) (err error) { } // command sends a command to the ssd1306 -func (s *SSD1306Driver) command(b byte) (err error) { - _, err = s.connection.Write([]byte{0x80, b}) +func (s *SSD1306Driver) command(b byte) error { + _, err := s.connection.Write([]byte{0x80, b}) return err } // commands sends a command sequence to the ssd1306 -func (s *SSD1306Driver) commands(commands []byte) (err error) { +func (s *SSD1306Driver) commands(commands []byte) error { var command []byte for _, d := range commands { command = append(command, []byte{0x80, d}...) } - _, err = s.connection.Write(command) + _, err := s.connection.Write(command) return err } -func (s *SSD1306Driver) initialize() (err error) { +func (s *SSD1306Driver) initialize() error { // check device size for supported resolutions switch { case s.displayWidth == 128 && s.displayHeight == 64: @@ -394,11 +391,9 @@ func (s *SSD1306Driver) initialize() (err error) { s.initSequence.contrast = 0x9F s.initSequence.prechargePeriod = 0x22 } - if err = s.Init(); err != nil { - return err - } - if err = s.On(); err != nil { + if err := s.Init(); err != nil { return err } - return nil + + return s.On() } diff --git a/drivers/i2c/ssd1306_driver_test.go b/drivers/i2c/ssd1306_driver_test.go index 204c6dbd8..58cec23ef 100644 --- a/drivers/i2c/ssd1306_driver_test.go +++ b/drivers/i2c/ssd1306_driver_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert // ok here package i2c import ( @@ -9,6 +10,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/i2c/th02_driver.go b/drivers/i2c/th02_driver.go index bf29309e7..2680a4239 100644 --- a/drivers/i2c/th02_driver.go +++ b/drivers/i2c/th02_driver.go @@ -154,6 +154,8 @@ func (s *TH02Driver) Heater() (bool, error) { } // Sample returns the temperature in celsius and relative humidity for one sample +// +//nolint:nonamedreturns // is sufficient here func (s *TH02Driver) Sample() (temperature float32, relhumidity float32, _ error) { s.mutex.Lock() defer s.mutex.Unlock() @@ -179,8 +181,7 @@ func (s *TH02Driver) Sample() (temperature float32, relhumidity float32, _ error } temperature = float32(rawt>>2)/32.0 - 50.0 - switch s.Units { - case "F": + if s.Units == "F" { temperature = 9.0/5.0*temperature + 32.0 } diff --git a/drivers/i2c/th02_driver_test.go b/drivers/i2c/th02_driver_test.go index 369900629..ca8bc5392 100644 --- a/drivers/i2c/th02_driver_test.go +++ b/drivers/i2c/th02_driver_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/i2c/tsl2561_driver.go b/drivers/i2c/tsl2561_driver.go index cc3ff7160..44e94ac58 100644 --- a/drivers/i2c/tsl2561_driver.go +++ b/drivers/i2c/tsl2561_driver.go @@ -241,41 +241,44 @@ func (d *TSL2561Driver) SetGain(gain TSL2561Gain) error { // GetLuminocity gets the broadband and IR only values from the TSL2561, // adjusting gain if auto-gain is enabled -func (d *TSL2561Driver) GetLuminocity() (broadband uint16, ir uint16, err error) { +func (d *TSL2561Driver) GetLuminocity() (uint16, uint16, error) { // if auto gain disabled get a single reading and continue if !d.autoGain { - broadband, ir, err = d.getData() - return + return d.getData() } agcCheck := false hi, lo := d.getHiLo() // Read data until we find a valid range + var broadband uint16 + var ir uint16 + var err error valid := false for { broadband, ir, err = d.getData() if err != nil { - return + return broadband, ir, err } // Run an auto-gain check if we haven't already done so if !agcCheck { - if (broadband < lo) && (d.gain == TSL2561Gain1X) { + switch { + case (broadband < lo) && (d.gain == TSL2561Gain1X): // increase gain and try again err = d.SetGain(TSL2561Gain16X) if err != nil { - return + return broadband, ir, err } agcCheck = true - } else if (broadband > hi) && (d.gain == TSL2561Gain16X) { + case (broadband > hi) && (d.gain == TSL2561Gain16X): // drop gain and try again err = d.SetGain(TSL2561Gain1X) if err != nil { - return + return broadband, ir, err } agcCheck = true - } else { + default: // Reading is either valid, or we're already at the chips // limits valid = true @@ -292,12 +295,12 @@ func (d *TSL2561Driver) GetLuminocity() (broadband uint16, ir uint16, err error) } } - return + return broadband, ir, err } // CalculateLux converts raw sensor values to the standard SI Lux equivalent. // Returns 65536 if the sensor is saturated. -func (d *TSL2561Driver) CalculateLux(broadband uint16, ir uint16) (lux uint32) { +func (d *TSL2561Driver) CalculateLux(broadband uint16, ir uint16) uint32 { var channel1 uint32 var channel0 uint32 @@ -336,45 +339,44 @@ func (d *TSL2561Driver) CalculateLux(broadband uint16, ir uint16) (lux uint32) { temp += (1 << (tsl2561LuxLuxScale - 1)) // Strip off fractional portion - lux = temp >> tsl2561LuxLuxScale + lux := temp >> tsl2561LuxLuxScale return lux } -func (d *TSL2561Driver) enable() (err error) { - err = d.connection.WriteByteData(uint8(tsl2561CommandBit|tsl2561RegisterControl), tsl2561ControlPowerOn) - return err +func (d *TSL2561Driver) enable() error { + return d.connection.WriteByteData(uint8(tsl2561CommandBit|tsl2561RegisterControl), tsl2561ControlPowerOn) } -func (d *TSL2561Driver) disable() (err error) { - err = d.connection.WriteByteData(uint8(tsl2561CommandBit|tsl2561RegisterControl), tsl2561ControlPowerOff) - return err +func (d *TSL2561Driver) disable() error { + return d.connection.WriteByteData(uint8(tsl2561CommandBit|tsl2561RegisterControl), tsl2561ControlPowerOff) } -func (d *TSL2561Driver) getData() (broadband uint16, ir uint16, err error) { - if err = d.enable(); err != nil { - return +func (d *TSL2561Driver) getData() (uint16, uint16, error) { + if err := d.enable(); err != nil { + return 0, 0, err } d.waitForADC() // Reads a two byte value from channel 0 (visible + infrared) - broadband, err = d.connection.ReadWordData(tsl2561CommandBit | tsl2561WordBit | tsl2561RegisterChan0Low) + broadband, err := d.connection.ReadWordData(tsl2561CommandBit | tsl2561WordBit | tsl2561RegisterChan0Low) if err != nil { - return + return 0, 0, err } // Reads a two byte value from channel 1 (infrared) - ir, err = d.connection.ReadWordData(tsl2561CommandBit | tsl2561WordBit | tsl2561RegisterChan1Low) + ir, err := d.connection.ReadWordData(tsl2561CommandBit | tsl2561WordBit | tsl2561RegisterChan1Low) if err != nil { - return + return 0, 0, err } err = d.disable() - return + return broadband, ir, err } +//nolint:nonamedreturns // is sufficient here func (d *TSL2561Driver) getHiLo() (hi, lo uint16) { switch d.integrationTime { case TSL2561IntegrationTime13MS: @@ -390,6 +392,7 @@ func (d *TSL2561Driver) getHiLo() (hi, lo uint16) { return } +//nolint:nonamedreturns // is sufficient here func (d *TSL2561Driver) getClipScaling() (clipThreshold uint16, chScale uint32) { switch d.integrationTime { case TSL2561IntegrationTime13MS: @@ -405,6 +408,7 @@ func (d *TSL2561Driver) getClipScaling() (clipThreshold uint16, chScale uint32) return } +//nolint:nonamedreturns // is sufficient here func (d *TSL2561Driver) getBM(ratio uint32) (b uint32, m uint32) { switch { case ratio <= tsl2561LuxK1T: diff --git a/drivers/i2c/tsl2561_driver_test.go b/drivers/i2c/tsl2561_driver_test.go index a027b9abf..573a2c89f 100644 --- a/drivers/i2c/tsl2561_driver_test.go +++ b/drivers/i2c/tsl2561_driver_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/i2c/wiichuck_driver.go b/drivers/i2c/wiichuck_driver.go index fc2d305bd..c78f0b67a 100644 --- a/drivers/i2c/wiichuck_driver.go +++ b/drivers/i2c/wiichuck_driver.go @@ -158,7 +158,7 @@ func (w *WiichuckDriver) parse(value []byte) { } // reads from adaptor using specified interval to update with new value -func (w *WiichuckDriver) initialize() (err error) { +func (w *WiichuckDriver) initialize() error { go func() { for { if _, err := w.connection.Write([]byte{0x40, 0x00}); err != nil { @@ -186,5 +186,5 @@ func (w *WiichuckDriver) initialize() (err error) { time.Sleep(w.interval) } }() - return + return nil } diff --git a/drivers/i2c/wiichuck_driver_test.go b/drivers/i2c/wiichuck_driver_test.go index 348336d9a..0f2b40109 100644 --- a/drivers/i2c/wiichuck_driver_test.go +++ b/drivers/i2c/wiichuck_driver_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/i2c/yl40_driver.go b/drivers/i2c/yl40_driver.go index 4509ddfeb..b740150fe 100644 --- a/drivers/i2c/yl40_driver.go +++ b/drivers/i2c/yl40_driver.go @@ -186,7 +186,7 @@ func WithYL40OutputScaler(scaler func(input float64) (value int)) func(Config) { } // Start initializes the driver -func (y *YL40Driver) Start() (err error) { +func (y *YL40Driver) Start() error { // must be the first one if err := y.PCF8591Driver.Start(); err != nil { return err @@ -210,7 +210,7 @@ func (y *YL40Driver) Start() (err error) { } // Halt stops the driver -func (y *YL40Driver) Halt() (err error) { +func (y *YL40Driver) Halt() error { // we try halt on each device, not stopping on the first error var errors []string if err := y.aBri.Halt(); err != nil { @@ -240,7 +240,7 @@ func (y *YL40Driver) Halt() (err error) { // Read returns the current reading from the given pin of the driver // For the analog output pin the last written value is returned -func (y *YL40Driver) Read(pin YL40Pin) (val float64, err error) { +func (y *YL40Driver) Read(pin YL40Pin) (float64, error) { switch pin { case YL40Bri: return y.aBri.Read() @@ -258,27 +258,27 @@ func (y *YL40Driver) Read(pin YL40Pin) (val float64, err error) { } // ReadBrightness returns the current reading from brightness pin of the driver -func (y *YL40Driver) ReadBrightness() (val float64, err error) { +func (y *YL40Driver) ReadBrightness() (float64, error) { return y.Read(YL40Bri) } // ReadTemperature returns the current reading from temperature pin of the driver -func (y *YL40Driver) ReadTemperature() (val float64, err error) { +func (y *YL40Driver) ReadTemperature() (float64, error) { return y.Read(YL40Temp) } // ReadAIN2 returns the current reading from analog input pin 2 pin of the driver -func (y *YL40Driver) ReadAIN2() (val float64, err error) { +func (y *YL40Driver) ReadAIN2() (float64, error) { return y.Read(YL40AIN2) } // ReadPotentiometer returns the current reading from potentiometer pin of the driver -func (y *YL40Driver) ReadPotentiometer() (val float64, err error) { +func (y *YL40Driver) ReadPotentiometer() (float64, error) { return y.Read(YL40Poti) } // Value returns the last read or written value from the given pin of the driver -func (y *YL40Driver) Value(pin YL40Pin) (val float64, err error) { +func (y *YL40Driver) Value(pin YL40Pin) (float64, error) { switch pin { case YL40Bri: return y.aBri.Value(), nil @@ -296,31 +296,31 @@ func (y *YL40Driver) Value(pin YL40Pin) (val float64, err error) { } // Brightness returns the last read brightness of the driver -func (y *YL40Driver) Brightness() (val float64, err error) { +func (y *YL40Driver) Brightness() (float64, error) { return y.Value(YL40Bri) } // Temperature returns the last read temperature of the driver -func (y *YL40Driver) Temperature() (val float64, err error) { +func (y *YL40Driver) Temperature() (float64, error) { return y.Value(YL40Temp) } // AIN2 returns the last read analog input value of the driver -func (y *YL40Driver) AIN2() (val float64, err error) { +func (y *YL40Driver) AIN2() (float64, error) { return y.Value(YL40AIN2) } // Potentiometer returns the last read potentiometer value of the driver -func (y *YL40Driver) Potentiometer() (val float64, err error) { +func (y *YL40Driver) Potentiometer() (float64, error) { return y.Value(YL40Poti) } // AOUT returns the last written value of the driver -func (y *YL40Driver) AOUT() (val float64, err error) { +func (y *YL40Driver) AOUT() (float64, error) { return y.Value(YL40AOUT) } // Write writes the given value to the analog output -func (y *YL40Driver) Write(val float64) (err error) { +func (y *YL40Driver) Write(val float64) error { return y.aOut.Write(val) } diff --git a/drivers/i2c/yl40_driver_test.go b/drivers/i2c/yl40_driver_test.go index 2975ceec1..91ea22ffb 100644 --- a/drivers/i2c/yl40_driver_test.go +++ b/drivers/i2c/yl40_driver_test.go @@ -56,10 +56,10 @@ func TestYL40DriverWithYL40Interval(t *testing.T) { func TestYL40DriverWithYL40InputScaler(t *testing.T) { // arrange yl := NewYL40Driver(newI2cTestAdaptor()) - f1 := func(input int) (value float64) { return 0.1 } - 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 } + f1 := func(input int) float64 { return 0.1 } + f2 := func(input int) float64 { return 0.2 } + f3 := func(input int) float64 { return 0.3 } + f4 := func(input int) float64 { return 0.4 } // act WithYL40InputScaler(YL40Bri, f1)(yl) WithYL40InputScaler(YL40Temp, f2)(yl) @@ -75,7 +75,7 @@ func TestYL40DriverWithYL40InputScaler(t *testing.T) { func TestYL40DriverWithYL40WithYL40OutputScaler(t *testing.T) { // arrange yl := NewYL40Driver(newI2cTestAdaptor()) - fo := func(input float64) (value int) { return 123 } + fo := func(input float64) int { return 123 } // act WithYL40OutputScaler(fo)(yl) // assert diff --git a/drivers/spi/apa102_test.go b/drivers/spi/apa102_test.go index bca281a5f..5a032d95d 100644 --- a/drivers/spi/apa102_test.go +++ b/drivers/spi/apa102_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/spi/mcp3002.go b/drivers/spi/mcp3002.go index 5358f67e6..44b0b9911 100644 --- a/drivers/spi/mcp3002.go +++ b/drivers/spi/mcp3002.go @@ -56,9 +56,7 @@ func (d *MCP3002Driver) Read(channel int) (int, error) { } // AnalogRead returns value from analog reading of specified pin -func (d *MCP3002Driver) AnalogRead(pin string) (value int, err error) { +func (d *MCP3002Driver) AnalogRead(pin string) (int, error) { channel, _ := strconv.Atoi(pin) - value, err = d.Read(channel) - - return + return d.Read(channel) } diff --git a/drivers/spi/mcp3002_test.go b/drivers/spi/mcp3002_test.go index c8b341d17..1b8c5f914 100644 --- a/drivers/spi/mcp3002_test.go +++ b/drivers/spi/mcp3002_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/aio" ) diff --git a/drivers/spi/mcp3004.go b/drivers/spi/mcp3004.go index eb5d77ee8..3f7b739a0 100644 --- a/drivers/spi/mcp3004.go +++ b/drivers/spi/mcp3004.go @@ -37,7 +37,7 @@ func NewMCP3004Driver(a Connector, options ...func(Config)) *MCP3004Driver { } // Read reads the current analog data for the desired channel. -func (d *MCP3004Driver) Read(channel int) (result int, err error) { +func (d *MCP3004Driver) Read(channel int) (int, error) { if channel < 0 || channel > MCP3004DriverMaxChannel-1 { return 0, fmt.Errorf("Invalid channel '%d' for read", channel) } @@ -49,18 +49,17 @@ func (d *MCP3004Driver) Read(channel int) (result int, err error) { rx := make([]byte, 3) - err = d.connection.ReadCommandData(tx, rx) - if err == nil && len(rx) == 3 { - result = int((rx[1]&0x3))<<8 + int(rx[2]) + if err := d.connection.ReadCommandData(tx, rx); err != nil || len(rx) != 3 { + return 0, err } - return result, err + result := int((rx[1]&0x3))<<8 + int(rx[2]) + + return result, nil } // AnalogRead returns value from analog reading of specified pin -func (d *MCP3004Driver) AnalogRead(pin string) (value int, err error) { +func (d *MCP3004Driver) AnalogRead(pin string) (int, error) { channel, _ := strconv.Atoi(pin) - value, err = d.Read(channel) - - return + return d.Read(channel) } diff --git a/drivers/spi/mcp3004_test.go b/drivers/spi/mcp3004_test.go index c6b0660b7..2eeb69408 100644 --- a/drivers/spi/mcp3004_test.go +++ b/drivers/spi/mcp3004_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/aio" ) diff --git a/drivers/spi/mcp3008.go b/drivers/spi/mcp3008.go index 15a1f1622..ca6044967 100644 --- a/drivers/spi/mcp3008.go +++ b/drivers/spi/mcp3008.go @@ -37,7 +37,7 @@ func NewMCP3008Driver(a Connector, options ...func(Config)) *MCP3008Driver { } // Read reads the current analog data for the desired channel. -func (d *MCP3008Driver) Read(channel int) (result int, err error) { +func (d *MCP3008Driver) Read(channel int) (int, error) { if channel < 0 || channel > MCP3008DriverMaxChannel-1 { return 0, fmt.Errorf("Invalid channel '%d' for read", channel) } @@ -49,18 +49,17 @@ func (d *MCP3008Driver) Read(channel int) (result int, err error) { rx := make([]byte, 3) - err = d.connection.ReadCommandData(tx, rx) - if err == nil && len(rx) == 3 { - result = int((rx[1]&0x3))<<8 + int(rx[2]) + if err := d.connection.ReadCommandData(tx, rx); err != nil || len(rx) != 3 { + return 0, err } - return result, err + result := int((rx[1]&0x3))<<8 + int(rx[2]) + + return result, nil } // AnalogRead returns value from analog reading of specified pin -func (d *MCP3008Driver) AnalogRead(pin string) (value int, err error) { +func (d *MCP3008Driver) AnalogRead(pin string) (int, error) { channel, _ := strconv.Atoi(pin) - value, err = d.Read(channel) - - return + return d.Read(channel) } diff --git a/drivers/spi/mcp3008_test.go b/drivers/spi/mcp3008_test.go index 4ad5d91a6..6c85a9b91 100644 --- a/drivers/spi/mcp3008_test.go +++ b/drivers/spi/mcp3008_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/aio" ) diff --git a/drivers/spi/mcp3202.go b/drivers/spi/mcp3202.go index 6c687c8a4..b1be8a0d0 100644 --- a/drivers/spi/mcp3202.go +++ b/drivers/spi/mcp3202.go @@ -39,7 +39,7 @@ func NewMCP3202Driver(a Connector, options ...func(Config)) *MCP3202Driver { } // Read reads the current analog data for the desired channel. -func (d *MCP3202Driver) Read(channel int) (result int, err error) { +func (d *MCP3202Driver) Read(channel int) (int, error) { if channel < 0 || channel > MCP3202DriverMaxChannel-1 { return 0, fmt.Errorf("Invalid channel '%d' for read", channel) } @@ -51,21 +51,22 @@ func (d *MCP3202Driver) Read(channel int) (result int, err error) { rx := make([]byte, 3) - err = d.connection.ReadCommandData(tx, rx) - if err == nil && len(rx) == 3 { - result = int((rx[1]&0xf))<<8 + int(rx[2]) + if err := d.connection.ReadCommandData(tx, rx); err != nil || len(rx) != 3 { + return 0, err } - return result, err + result := int((rx[1]&0xf))<<8 + int(rx[2]) + + return result, nil } // AnalogRead returns value from analog reading of specified pin, scaled to 0-1023 value. -func (d *MCP3202Driver) AnalogRead(pin string) (value int, err error) { +func (d *MCP3202Driver) AnalogRead(pin string) (int, error) { channel, _ := strconv.Atoi(pin) - value, err = d.Read(channel) + value, err := d.Read(channel) if err != nil { value = int(gobot.ToScale(gobot.FromScale(float64(value), 0, 4095), 0, 1023)) } - return + return value, err } diff --git a/drivers/spi/mcp3202_test.go b/drivers/spi/mcp3202_test.go index ec414964b..15729617f 100644 --- a/drivers/spi/mcp3202_test.go +++ b/drivers/spi/mcp3202_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/aio" ) diff --git a/drivers/spi/mcp3204.go b/drivers/spi/mcp3204.go index d8deaf42f..09858a247 100644 --- a/drivers/spi/mcp3204.go +++ b/drivers/spi/mcp3204.go @@ -39,7 +39,7 @@ func NewMCP3204Driver(a Connector, options ...func(Config)) *MCP3204Driver { } // Read reads the current analog data for the desired channel. -func (d *MCP3204Driver) Read(channel int) (result int, err error) { +func (d *MCP3204Driver) Read(channel int) (int, error) { if channel < 0 || channel > MCP3204DriverMaxChannel-1 { return 0, fmt.Errorf("Invalid channel '%d' for read", channel) } @@ -51,21 +51,22 @@ func (d *MCP3204Driver) Read(channel int) (result int, err error) { rx := make([]byte, 3) - err = d.connection.ReadCommandData(tx, rx) - if err == nil && len(rx) == 3 { - result = int((rx[1]&0xf))<<8 + int(rx[2]) + if err := d.connection.ReadCommandData(tx, rx); err != nil || len(rx) != 3 { + return 0, err } - return result, err + result := int((rx[1]&0xf))<<8 + int(rx[2]) + + return result, nil } // AnalogRead returns value from analog reading of specified pin, scaled to 0-1023 value. -func (d *MCP3204Driver) AnalogRead(pin string) (value int, err error) { +func (d *MCP3204Driver) AnalogRead(pin string) (int, error) { channel, _ := strconv.Atoi(pin) - value, err = d.Read(channel) + value, err := d.Read(channel) if err != nil { value = int(gobot.ToScale(gobot.FromScale(float64(value), 0, 4095), 0, 1023)) } - return + return value, err } diff --git a/drivers/spi/mcp3204_test.go b/drivers/spi/mcp3204_test.go index c948fe630..11fc103e3 100644 --- a/drivers/spi/mcp3204_test.go +++ b/drivers/spi/mcp3204_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/aio" ) diff --git a/drivers/spi/mcp3208.go b/drivers/spi/mcp3208.go index 274e46e74..d17fa5137 100644 --- a/drivers/spi/mcp3208.go +++ b/drivers/spi/mcp3208.go @@ -39,7 +39,7 @@ func NewMCP3208Driver(a Connector, options ...func(Config)) *MCP3208Driver { } // Read reads the current analog data for the desired channel. -func (d *MCP3208Driver) Read(channel int) (result int, err error) { +func (d *MCP3208Driver) Read(channel int) (int, error) { if channel < 0 || channel > MCP3208DriverMaxChannel-1 { return 0, fmt.Errorf("Invalid channel '%d' for read", channel) } @@ -51,21 +51,22 @@ func (d *MCP3208Driver) Read(channel int) (result int, err error) { rx := make([]byte, 3) - err = d.connection.ReadCommandData(tx, rx) - if err == nil && len(rx) == 3 { - result = int((rx[1]&0xf))<<8 + int(rx[2]) + if err := d.connection.ReadCommandData(tx, rx); err != nil || len(rx) != 3 { + return 0, err } - return result, err + result := int((rx[1]&0xf))<<8 + int(rx[2]) + + return result, nil } // AnalogRead returns value from analog reading of specified pin, scaled to 0-1023 value. -func (d *MCP3208Driver) AnalogRead(pin string) (value int, err error) { +func (d *MCP3208Driver) AnalogRead(pin string) (int, error) { channel, _ := strconv.Atoi(pin) - value, err = d.Read(channel) + value, err := d.Read(channel) if err != nil { value = int(gobot.ToScale(gobot.FromScale(float64(value), 0, 4095), 0, 1023)) } - return + return value, err } diff --git a/drivers/spi/mcp3208_test.go b/drivers/spi/mcp3208_test.go index 9150aa61d..7bfe0d32f 100644 --- a/drivers/spi/mcp3208_test.go +++ b/drivers/spi/mcp3208_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/aio" ) diff --git a/drivers/spi/mcp3304.go b/drivers/spi/mcp3304.go index 1f6aa58fb..8a5b48be6 100644 --- a/drivers/spi/mcp3304.go +++ b/drivers/spi/mcp3304.go @@ -39,7 +39,7 @@ func NewMCP3304Driver(a Connector, options ...func(Config)) *MCP3304Driver { } // Read reads the current analog data for the desired channel. -func (d *MCP3304Driver) Read(channel int) (result int, err error) { +func (d *MCP3304Driver) Read(channel int) (int, error) { if channel < 0 || channel > MCP3304DriverMaxChannel-1 { return 0, fmt.Errorf("Invalid channel '%d' for read", channel) } @@ -51,21 +51,22 @@ func (d *MCP3304Driver) Read(channel int) (result int, err error) { rx := make([]byte, 3) - err = d.connection.ReadCommandData(tx, rx) - if err == nil && len(rx) == 3 { - result = int((rx[1]&0xf))<<8 + int(rx[2]) + if err := d.connection.ReadCommandData(tx, rx); err != nil || len(rx) != 3 { + return 0, err } - return result, err + result := int((rx[1]&0xf))<<8 + int(rx[2]) + + return result, nil } // AnalogRead returns value from analog reading of specified pin, scaled to 0-1023 value. -func (d *MCP3304Driver) AnalogRead(pin string) (value int, err error) { +func (d *MCP3304Driver) AnalogRead(pin string) (int, error) { channel, _ := strconv.Atoi(pin) - value, err = d.Read(channel) + value, err := d.Read(channel) if err != nil { value = int(gobot.ToScale(gobot.FromScale(float64(value), 0, 4095), 0, 1023)) } - return + return value, err } diff --git a/drivers/spi/mcp3304_test.go b/drivers/spi/mcp3304_test.go index b9a3b3860..e928795fe 100644 --- a/drivers/spi/mcp3304_test.go +++ b/drivers/spi/mcp3304_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/aio" ) diff --git a/drivers/spi/mfrc522_driver_test.go b/drivers/spi/mfrc522_driver_test.go index bbfc54715..1bd88baca 100644 --- a/drivers/spi/mfrc522_driver_test.go +++ b/drivers/spi/mfrc522_driver_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/spi/spi_connection_test.go b/drivers/spi/spi_connection_test.go index d849e96b5..1d4d94ad7 100644 --- a/drivers/spi/spi_connection_test.go +++ b/drivers/spi/spi_connection_test.go @@ -5,6 +5,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/system" ) diff --git a/drivers/spi/spi_driver.go b/drivers/spi/spi_driver.go index b18acc6a3..b25878596 100644 --- a/drivers/spi/spi_driver.go +++ b/drivers/spi/spi_driver.go @@ -1,6 +1,7 @@ package spi import ( + "log" "sync" "gobot.io/x/gobot/v2" @@ -108,7 +109,14 @@ func (d *Driver) Name() string { return d.name } func (d *Driver) SetName(n string) { d.name = n } // Connection returns the Connection of the device. -func (d *Driver) Connection() gobot.Connection { return d.connector.(gobot.Connection) } +func (d *Driver) Connection() gobot.Connection { + if conn, ok := d.connector.(gobot.Connection); ok { + return conn + } + + log.Printf("%s has no gobot connection\n", d.name) + return nil +} // Start initializes the driver. func (d *Driver) Start() error { @@ -130,7 +138,7 @@ func (d *Driver) Start() error { } // Halt stops the driver. -func (d *Driver) Halt() (err error) { +func (d *Driver) Halt() error { d.mutex.Lock() defer d.mutex.Unlock() diff --git a/drivers/spi/spi_driver_test.go b/drivers/spi/spi_driver_test.go index 60ecb2b75..9f35c5591 100644 --- a/drivers/spi/spi_driver_test.go +++ b/drivers/spi/spi_driver_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/drivers/spi/ssd1306_driver.go b/drivers/spi/ssd1306_driver.go index e57ac28a5..819a6a2a7 100644 --- a/drivers/spi/ssd1306_driver.go +++ b/drivers/spi/ssd1306_driver.go @@ -169,11 +169,13 @@ func NewSSD1306Driver(a gobot.Adaptor, options ...func(Config)) *SSD1306Driver { err := s.Clear() return map[string]interface{}{"err": err} }) + //nolint:forcetypeassert // ok here s.AddCommand("SetContrast", func(params map[string]interface{}) interface{} { contrast := params["contrast"].(byte) err := s.SetContrast(contrast) return map[string]interface{}{"err": err} }) + //nolint:forcetypeassert // ok here s.AddCommand("Set", func(params map[string]interface{}) interface{} { x := params["x"].(int) y := params["y"].(int) diff --git a/drivers/spi/ssd1306_driver_test.go b/drivers/spi/ssd1306_driver_test.go index 57b39b7fc..b72765196 100644 --- a/drivers/spi/ssd1306_driver_test.go +++ b/drivers/spi/ssd1306_driver_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -49,65 +50,65 @@ type gpioTestAdaptor struct { port string mtx sync.Mutex Connector - digitalWriteFunc func() (err error) - servoWriteFunc func() (err error) - pwmWriteFunc func() (err error) + digitalWriteFunc func() error + servoWriteFunc func() error + pwmWriteFunc func() error analogReadFunc func() (val int, err error) digitalReadFunc func() (val int, err error) } -func (t *gpioTestAdaptor) ServoWrite(string, byte) (err error) { +func (t *gpioTestAdaptor) ServoWrite(string, byte) error { t.mtx.Lock() defer t.mtx.Unlock() return t.servoWriteFunc() } -func (t *gpioTestAdaptor) PwmWrite(string, byte) (err error) { +func (t *gpioTestAdaptor) PwmWrite(string, byte) error { t.mtx.Lock() defer t.mtx.Unlock() return t.pwmWriteFunc() } -func (t *gpioTestAdaptor) AnalogRead(string) (val int, err error) { +func (t *gpioTestAdaptor) AnalogRead(string) (int, error) { t.mtx.Lock() defer t.mtx.Unlock() return t.analogReadFunc() } -func (t *gpioTestAdaptor) DigitalRead(string) (val int, err error) { +func (t *gpioTestAdaptor) DigitalRead(string) (int, error) { t.mtx.Lock() defer t.mtx.Unlock() return t.digitalReadFunc() } -func (t *gpioTestAdaptor) DigitalWrite(string, byte) (err error) { +func (t *gpioTestAdaptor) DigitalWrite(string, byte) error { t.mtx.Lock() defer t.mtx.Unlock() return t.digitalWriteFunc() } -func (t *gpioTestAdaptor) Connect() (err error) { return } -func (t *gpioTestAdaptor) Finalize() (err error) { return } -func (t *gpioTestAdaptor) Name() string { return t.name } -func (t *gpioTestAdaptor) SetName(n string) { t.name = n } -func (t *gpioTestAdaptor) Port() string { return t.port } +func (t *gpioTestAdaptor) Connect() error { return nil } +func (t *gpioTestAdaptor) Finalize() error { return nil } +func (t *gpioTestAdaptor) Name() string { return t.name } +func (t *gpioTestAdaptor) SetName(n string) { t.name = n } +func (t *gpioTestAdaptor) Port() string { return t.port } func newGpioTestAdaptor() *gpioTestAdaptor { a := newSpiTestAdaptor() return &gpioTestAdaptor{ port: "/dev/null", - digitalWriteFunc: func() (err error) { + digitalWriteFunc: func() error { return nil }, - servoWriteFunc: func() (err error) { + servoWriteFunc: func() error { return nil }, - pwmWriteFunc: func() (err error) { + pwmWriteFunc: func() error { return nil }, - analogReadFunc: func() (val int, err error) { + analogReadFunc: func() (int, error) { return 99, nil }, - digitalReadFunc: func() (val int, err error) { + digitalReadFunc: func() (int, error) { return 1, nil }, Connector: a, diff --git a/eventer.go b/eventer.go index dacda7c5a..fce3c2362 100644 --- a/eventer.go +++ b/eventer.go @@ -46,10 +46,10 @@ type Eventer interface { Unsubscribe(events eventChannel) // Event handler - On(name string, f func(s interface{})) (err error) + On(name string, f func(s interface{})) error // Event handler, only executes one time - Once(name string, f func(s interface{})) (err error) + Once(name string, f func(s interface{})) error } // NewEventer returns a new Eventer. @@ -119,7 +119,7 @@ func (e *eventer) Unsubscribe(events eventChannel) { } // On executes the event handler f when e is Published to. -func (e *eventer) On(n string, f func(s interface{})) (err error) { +func (e *eventer) On(n string, f func(s interface{})) error { out := e.Subscribe() go func() { for { @@ -130,11 +130,11 @@ func (e *eventer) On(n string, f func(s interface{})) (err error) { } }() - return + return nil } // Once is similar to On except that it only executes f one time. -func (e *eventer) Once(n string, f func(s interface{})) (err error) { +func (e *eventer) Once(n string, f func(s interface{})) error { out := e.Subscribe() go func() { ProcessEvents: @@ -147,5 +147,5 @@ func (e *eventer) Once(n string, f func(s interface{})) (err error) { } }() - return + return nil } diff --git a/examples/batty.go b/examples/batty.go index 918e99440..7ea6aa7f4 100644 --- a/examples/batty.go +++ b/examples/batty.go @@ -52,11 +52,11 @@ type loopbackAdaptor struct { port string } -func (t *loopbackAdaptor) Finalize() (err error) { return } -func (t *loopbackAdaptor) Connect() (err error) { return } -func (t *loopbackAdaptor) Name() string { return t.name } -func (t *loopbackAdaptor) SetName(n string) { t.name = n } -func (t *loopbackAdaptor) Port() string { return t.port } +func (t *loopbackAdaptor) Finalize() error { return nil } +func (t *loopbackAdaptor) Connect() error { return nil } +func (t *loopbackAdaptor) Name() string { return t.name } +func (t *loopbackAdaptor) SetName(n string) { t.name = n } +func (t *loopbackAdaptor) Port() string { return t.port } func NewLoopbackAdaptor(port string) *loopbackAdaptor { return &loopbackAdaptor{ @@ -75,8 +75,8 @@ type pingDriver struct { gobot.Commander } -func (t *pingDriver) Start() (err error) { return } -func (t *pingDriver) Halt() (err error) { return } +func (t *pingDriver) Start() error { return nil } +func (t *pingDriver) Halt() error { return nil } func (t *pingDriver) Name() string { return t.name } func (t *pingDriver) SetName(n string) { t.name = n } func (t *pingDriver) Pin() string { return t.pin } diff --git a/examples/raspi_adafruit2327_servo.go b/examples/raspi_adafruit2327_servo.go index b34f1b6c4..9a93aa985 100644 --- a/examples/raspi_adafruit2327_servo.go +++ b/examples/raspi_adafruit2327_servo.go @@ -51,7 +51,7 @@ func main() { robot.Start() } -func adafruitServoMotorRunner(a *i2c.Adafruit2327Driver) (err error) { +func adafruitServoMotorRunner(a *i2c.Adafruit2327Driver) error { log.Printf("Servo Motor Run Loop...\n") var channel byte = 1 @@ -59,30 +59,30 @@ func adafruitServoMotorRunner(a *i2c.Adafruit2327Driver) (err error) { // Do not need to set this every run loop freq := 60.0 - if err = a.SetServoMotorFreq(freq); err != nil { + if err := a.SetServoMotorFreq(freq); err != nil { log.Printf("%s", err.Error()) - return + return err } // start in the middle of the 180-deg range pulse := degree2pulse(deg) - if err = a.SetServoMotorPulse(channel, 0, pulse); err != nil { + if err := a.SetServoMotorPulse(channel, 0, pulse); err != nil { log.Printf(err.Error()) - return + return err } // INCR pulse = degree2pulse(deg + degIncrease) - if err = a.SetServoMotorPulse(channel, 0, pulse); err != nil { + if err := a.SetServoMotorPulse(channel, 0, pulse); err != nil { log.Printf(err.Error()) - return + return err } time.Sleep(2000 * time.Millisecond) // DECR pulse = degree2pulse(deg - degIncrease) - if err = a.SetServoMotorPulse(channel, 0, pulse); err != nil { + if err := a.SetServoMotorPulse(channel, 0, pulse); err != nil { log.Printf(err.Error()) - return + return err } - return + return nil } func degree2pulse(deg int) int32 { diff --git a/examples/raspi_adafruit2348_dcmotor.go b/examples/raspi_adafruit2348_dcmotor.go index c617d0b48..b15967109 100644 --- a/examples/raspi_adafruit2348_dcmotor.go +++ b/examples/raspi_adafruit2348_dcmotor.go @@ -37,30 +37,30 @@ func main() { robot.Start() } -func adafruitDCMotorRunner(a *i2c.Adafruit2348Driver, dcMotor int) (err error) { +func adafruitDCMotorRunner(a *i2c.Adafruit2348Driver, dcMotor int) error { log.Printf("DC Motor Run Loop...\n") // set the speed: var speed int32 = 255 // 255 = full speed! - if err = a.SetDCMotorSpeed(dcMotor, speed); err != nil { - return + if err := a.SetDCMotorSpeed(dcMotor, speed); err != nil { + return err } // run FORWARD - if err = a.RunDCMotor(dcMotor, i2c.Adafruit2348Forward); err != nil { - return + if err := a.RunDCMotor(dcMotor, i2c.Adafruit2348Forward); err != nil { + return err } // Sleep and RELEASE time.Sleep(2000 * time.Millisecond) - if err = a.RunDCMotor(dcMotor, i2c.Adafruit2348Release); err != nil { - return + if err := a.RunDCMotor(dcMotor, i2c.Adafruit2348Release); err != nil { + return err } // run BACKWARD - if err = a.RunDCMotor(dcMotor, i2c.Adafruit2348Backward); err != nil { - return + if err := a.RunDCMotor(dcMotor, i2c.Adafruit2348Backward); err != nil { + return err } // Sleep and RELEASE time.Sleep(2000 * time.Millisecond) - if err = a.RunDCMotor(dcMotor, i2c.Adafruit2348Release); err != nil { - return + if err := a.RunDCMotor(dcMotor, i2c.Adafruit2348Release); err != nil { + return err } - return + return nil } diff --git a/examples/raspi_adafruit2348_stepper.go b/examples/raspi_adafruit2348_stepper.go index cbac4bc6e..c1eb80f38 100644 --- a/examples/raspi_adafruit2348_stepper.go +++ b/examples/raspi_adafruit2348_stepper.go @@ -37,7 +37,7 @@ func main() { robot.Start() } -func adafruitStepperMotorRunner(a *i2c.Adafruit2348Driver, motor int) (err error) { +func adafruitStepperMotorRunner(a *i2c.Adafruit2348Driver, motor int) error { log.Printf("Stepper Motor Run Loop...\n") // set the speed state: speed := 30 // rpm @@ -46,13 +46,13 @@ func adafruitStepperMotorRunner(a *i2c.Adafruit2348Driver, motor int) (err error a.SetStepperMotorSpeed(motor, speed) - if err = a.Step(motor, steps, i2c.Adafruit2348Forward, style); err != nil { + if err := a.Step(motor, steps, i2c.Adafruit2348Forward, style); err != nil { log.Printf(err.Error()) - return + return err } - if err = a.Step(motor, steps, i2c.Adafruit2348Backward, style); err != nil { + if err := a.Step(motor, steps, i2c.Adafruit2348Backward, style); err != nil { log.Printf(err.Error()) - return + return err } - return + return nil } diff --git a/helpers_test.go b/helpers_test.go index dee5d39a1..1c0206c00 100644 --- a/helpers_test.go +++ b/helpers_test.go @@ -24,12 +24,12 @@ type testDriver struct { } var ( - testDriverStart = func() (err error) { return } - testDriverHalt = func() (err error) { return } + testDriverStart = func() error { return nil } + testDriverHalt = func() error { return nil } ) -func (t *testDriver) Start() (err error) { return testDriverStart() } -func (t *testDriver) Halt() (err error) { return testDriverHalt() } +func (t *testDriver) Start() error { return testDriverStart() } +func (t *testDriver) Halt() error { return testDriverHalt() } func (t *testDriver) Name() string { return t.name } func (t *testDriver) SetName(n string) { t.name = n } func (t *testDriver) Pin() string { return t.pin } @@ -54,15 +54,15 @@ type testAdaptor struct { } var ( - testAdaptorConnect = func() (err error) { return } - testAdaptorFinalize = func() (err error) { return } + testAdaptorConnect = func() error { return nil } + testAdaptorFinalize = func() error { return nil } ) -func (t *testAdaptor) Finalize() (err error) { return testAdaptorFinalize() } -func (t *testAdaptor) Connect() (err error) { return testAdaptorConnect() } -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 (t *testAdaptor) Finalize() error { return testAdaptorFinalize() } +func (t *testAdaptor) Connect() error { return testAdaptorConnect() } +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 { //nolint:unparam // keep for tests return &testAdaptor{ diff --git a/master.go b/master.go index 9e16b269d..6119d6d12 100644 --- a/master.go +++ b/master.go @@ -88,7 +88,7 @@ func (g *Master) Stop() error { // Running returns if the Master is currently started or not func (g *Master) Running() bool { - return g.running.Load().(bool) + return g.running.Load().(bool) //nolint:forcetypeassert // no error return value, so there is no better way } // Robots returns all robots associated with this Gobot Master. diff --git a/master_test.go b/master_test.go index ac7cea80a..6ac1ddca6 100644 --- a/master_test.go +++ b/master_test.go @@ -90,7 +90,7 @@ func TestMasterStartAutoRun(t *testing.T) { func TestMasterStartDriverErrors(t *testing.T) { g := initTestMaster1Robot() e := errors.New("driver start error 1") - testDriverStart = func() (err error) { + testDriverStart = func() error { return e } @@ -102,13 +102,13 @@ func TestMasterStartDriverErrors(t *testing.T) { assert.Equal(t, want, g.Start()) require.NoError(t, g.Stop()) - testDriverStart = func() (err error) { return } + testDriverStart = func() error { return nil } } func TestMasterHaltFromRobotDriverErrors(t *testing.T) { g := initTestMaster1Robot() var ec int - testDriverHalt = func() (err error) { + testDriverHalt = func() error { ec++ return fmt.Errorf("driver halt error %d", ec) } @@ -126,7 +126,7 @@ func TestMasterHaltFromRobotDriverErrors(t *testing.T) { func TestMasterStartRobotAdaptorErrors(t *testing.T) { g := initTestMaster1Robot() var ec int - testAdaptorConnect = func() (err error) { + testAdaptorConnect = func() error { ec++ return fmt.Errorf("adaptor start error %d", ec) } @@ -141,13 +141,13 @@ func TestMasterStartRobotAdaptorErrors(t *testing.T) { assert.Equal(t, want, g.Start()) require.NoError(t, g.Stop()) - testAdaptorConnect = func() (err error) { return } + testAdaptorConnect = func() error { return nil } } func TestMasterFinalizeErrors(t *testing.T) { g := initTestMaster1Robot() var ec int - testAdaptorFinalize = func() (err error) { + testAdaptorFinalize = func() error { ec++ return fmt.Errorf("adaptor finalize error %d", ec) } diff --git a/platforms/adaptors/digitalpinsadaptor.go b/platforms/adaptors/digitalpinsadaptor.go index 08cd04da6..e62d91c70 100644 --- a/platforms/adaptors/digitalpinsadaptor.go +++ b/platforms/adaptors/digitalpinsadaptor.go @@ -50,7 +50,11 @@ type DigitalPinsAdaptor struct { // to the internal file name or chip/line nomenclature. This varies by each platform. If for some reasons the default // initializer is not suitable, it can be given by the option "WithDigitalPinInitializer()". This is especially needed, // if some values needs to be adjusted after the pin was created but before the pin is exported. -func NewDigitalPinsAdaptor(sys *system.Accesser, t digitalPinTranslator, options ...func(Optioner)) *DigitalPinsAdaptor { +func NewDigitalPinsAdaptor( + sys *system.Accesser, + t digitalPinTranslator, + options ...func(Optioner), +) *DigitalPinsAdaptor { a := &DigitalPinsAdaptor{ sys: sys, translate: t, @@ -219,10 +223,11 @@ func (a *DigitalPinsAdaptor) Connect() error { } // Finalize closes connection to digital pins -func (a *DigitalPinsAdaptor) Finalize() (err error) { +func (a *DigitalPinsAdaptor) Finalize() error { a.mutex.Lock() defer a.mutex.Unlock() + var err error for _, pin := range a.pins { if pin != nil { if e := pin.Unexport(); e != nil { @@ -232,7 +237,7 @@ func (a *DigitalPinsAdaptor) Finalize() (err error) { } a.pins = nil a.pinOptions = nil - return + return err } // DigitalPin returns a digital pin. If the pin is initially acquired, it is an input. @@ -395,7 +400,10 @@ func (a *DigitalPinsAdaptor) prepareDigitalPinPollForEdgeDetection( a.pinOptions[id] = append(a.pinOptions[id], system.WithPinPollForEdgeDetection(pollInterval, pollQuitChan)) } -func (a *DigitalPinsAdaptor) digitalPin(id string, opts ...func(gobot.DigitalPinOptioner) bool) (gobot.DigitalPinner, error) { +func (a *DigitalPinsAdaptor) digitalPin( + id string, + opts ...func(gobot.DigitalPinOptioner) bool, +) (gobot.DigitalPinner, error) { if a.pins == nil { return nil, fmt.Errorf("not connected for pin %s", id) } diff --git a/platforms/adaptors/digitalpinsadaptor_test.go b/platforms/adaptors/digitalpinsadaptor_test.go index 2e91c561a..ae0785df8 100644 --- a/platforms/adaptors/digitalpinsadaptor_test.go +++ b/platforms/adaptors/digitalpinsadaptor_test.go @@ -1,3 +1,4 @@ +//nolint:nonamedreturns // ok for tests package adaptors import ( @@ -10,6 +11,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/gpio" "gobot.io/x/gobot/v2/system" @@ -101,7 +103,7 @@ func TestDigitalPinsFinalize(t *testing.T) { require.NoError(t, a.DigitalWrite("3", 2)) delete(fs.Files, "/sys/class/gpio/unexport") err = a.Finalize() - assert.Contains(t, err.Error(), "/sys/class/gpio/unexport: no such file") + require.ErrorContains(t, err, "/sys/class/gpio/unexport: no such file") } func TestDigitalPinsReConnect(t *testing.T) { diff --git a/platforms/adaptors/i2cbusadaptor.go b/platforms/adaptors/i2cbusadaptor.go index cc1041972..401d6cf73 100644 --- a/platforms/adaptors/i2cbusadaptor.go +++ b/platforms/adaptors/i2cbusadaptor.go @@ -5,6 +5,7 @@ import ( "sync" multierror "github.com/hashicorp/go-multierror" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/i2c" "gobot.io/x/gobot/v2/system" diff --git a/platforms/adaptors/i2cbusadaptor_test.go b/platforms/adaptors/i2cbusadaptor_test.go index 116f97524..70d7ab8b8 100644 --- a/platforms/adaptors/i2cbusadaptor_test.go +++ b/platforms/adaptors/i2cbusadaptor_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2/drivers/i2c" "gobot.io/x/gobot/v2/system" ) @@ -94,7 +95,7 @@ func TestI2cFinalize(t *testing.T) { _, _ = con.Write([]byte{0xbf}) fs.WithCloseError = true err := a.Finalize() - assert.Contains(t, err.Error(), "close error") + require.ErrorContains(t, err, "close error") } func TestI2cReConnect(t *testing.T) { diff --git a/platforms/adaptors/pwmpinsadaptor.go b/platforms/adaptors/pwmpinsadaptor.go index b3a159fcf..4d0834adc 100644 --- a/platforms/adaptors/pwmpinsadaptor.go +++ b/platforms/adaptors/pwmpinsadaptor.go @@ -5,6 +5,7 @@ import ( "sync" multierror "github.com/hashicorp/go-multierror" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/system" ) @@ -90,10 +91,11 @@ func (a *PWMPinsAdaptor) Connect() error { } // Finalize closes connection to PWM pins. -func (a *PWMPinsAdaptor) Finalize() (err error) { +func (a *PWMPinsAdaptor) Finalize() error { a.mutex.Lock() defer a.mutex.Unlock() + var err error for _, pin := range a.pins { if pin != nil { if errs := pin.SetEnabled(false); errs != nil { @@ -109,13 +111,13 @@ func (a *PWMPinsAdaptor) Finalize() (err error) { } // PwmWrite writes a PWM signal to the specified pin. -func (a *PWMPinsAdaptor) PwmWrite(id string, val byte) (err error) { +func (a *PWMPinsAdaptor) PwmWrite(id string, val byte) error { a.mutex.Lock() defer a.mutex.Unlock() pin, err := a.pwmPin(id) if err != nil { - return + return err } period, err := pin.Period() if err != nil { @@ -126,13 +128,13 @@ func (a *PWMPinsAdaptor) PwmWrite(id string, val byte) (err error) { } // ServoWrite writes a servo signal to the specified pin. -func (a *PWMPinsAdaptor) ServoWrite(id string, angle byte) (err error) { +func (a *PWMPinsAdaptor) ServoWrite(id string, angle byte) error { a.mutex.Lock() defer a.mutex.Unlock() pin, err := a.pwmPin(id) if err != nil { - return + return err } period, err := pin.Period() if err != nil { diff --git a/platforms/adaptors/pwmpinsadaptor_test.go b/platforms/adaptors/pwmpinsadaptor_test.go index 94d8d61ca..0770695b6 100644 --- a/platforms/adaptors/pwmpinsadaptor_test.go +++ b/platforms/adaptors/pwmpinsadaptor_test.go @@ -1,16 +1,16 @@ +//nolint:nonamedreturns // ok for tests package adaptors import ( "fmt" - "log" "runtime" "strconv" - "strings" "sync" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/gpio" "gobot.io/x/gobot/v2/system" @@ -151,13 +151,13 @@ func TestPWMPinsFinalize(t *testing.T) { require.NoError(t, a.PwmWrite("33", 2)) delete(fs.Files, pwmUnexportPath) err = a.Finalize() - assert.Contains(t, err.Error(), pwmUnexportPath+": no such file") + require.ErrorContains(t, err, pwmUnexportPath+": no such file") // arrange write error require.NoError(t, a.Connect()) require.NoError(t, a.PwmWrite("33", 2)) fs.WithWriteError = true err = a.Finalize() - assert.Contains(t, err.Error(), "write error") + require.ErrorContains(t, err, "write error") } func TestPWMPinsReConnect(t *testing.T) { @@ -191,12 +191,12 @@ func TestPwmWrite(t *testing.T) { fs.WithWriteError = true err = a.PwmWrite("33", 100) - assert.Contains(t, err.Error(), "write error") + require.ErrorContains(t, err, "write error") fs.WithWriteError = false fs.WithReadError = true err = a.PwmWrite("33", 100) - assert.Contains(t, err.Error(), "read error") + require.ErrorContains(t, err, "read error") } func TestServoWrite(t *testing.T) { @@ -219,12 +219,12 @@ func TestServoWrite(t *testing.T) { fs.WithWriteError = true err = a.ServoWrite("33", 100) - assert.Contains(t, err.Error(), "write error") + require.ErrorContains(t, err, "write error") fs.WithWriteError = false fs.WithReadError = true err = a.ServoWrite("33", 100) - assert.Contains(t, err.Error(), "read error") + require.ErrorContains(t, err, "read error") } func TestSetPeriod(t *testing.T) { @@ -292,14 +292,16 @@ func Test_PWMPin(t *testing.T) { mockPaths: []string{}, translate: translator, pin: "33", - wantErr: "Export() failed for id 44 with : /sys/devices/platform/ff680020.pwm/pwm/pwmchip3/export: no such file", + wantErr: "Export() failed for id 44 with : " + + "/sys/devices/platform/ff680020.pwm/pwm/pwmchip3/export: no such file", }, "init_setenabled_error": { mockPaths: []string{pwmExportPath, pwmPeriodPath}, period: "1000", translate: translator, pin: "33", - wantErr: "SetEnabled(false) failed for id 44 with : /sys/devices/platform/ff680020.pwm/pwm/pwmchip3/pwm44/enable: no such file", + wantErr: "SetEnabled(false) failed for id 44 with : " + + "/sys/devices/platform/ff680020.pwm/pwm/pwmchip3/pwm44/enable: no such file", }, "init_setperiod_dutycycle_no_error": { mockPaths: []string{pwmExportPath, pwmEnablePath, pwmPeriodPath, pwmDutyCyclePath, pwmPolarityPath}, @@ -313,7 +315,8 @@ func Test_PWMPin(t *testing.T) { dutyCycle: "0", translate: translator, pin: "33", - wantErr: "SetPeriod(10000000) failed for id 44 with : /sys/devices/platform/ff680020.pwm/pwm/pwmchip3/pwm44/period: no such file", + wantErr: "SetPeriod(10000000) failed for id 44 with : " + + "/sys/devices/platform/ff680020.pwm/pwm/pwmchip3/pwm44/period: no such file", }, "init_setpolarity_error": { mockPaths: []string{pwmExportPath, pwmEnablePath, pwmPeriodPath, pwmDutyCyclePath}, @@ -321,7 +324,8 @@ func Test_PWMPin(t *testing.T) { dutyCycle: "0", translate: translator, pin: "33", - wantErr: "SetPolarity(normal) failed for id 44 with : /sys/devices/platform/ff680020.pwm/pwm/pwmchip3/pwm44/polarity: no such file", + wantErr: "SetPolarity(normal) failed for id 44 with : " + + "/sys/devices/platform/ff680020.pwm/pwm/pwmchip3/pwm44/polarity: no such file", }, "translate_error": { translate: func(string) (string, int, error) { return "", -1, fmt.Errorf(translateErr) }, @@ -350,10 +354,7 @@ func Test_PWMPin(t *testing.T) { require.NoError(t, err) assert.NotNil(t, got) } else { - if !strings.Contains(err.Error(), tc.wantErr) { - log.Println(err.Error()) - } - assert.Contains(t, err.Error(), tc.wantErr) + require.ErrorContains(t, err, tc.wantErr) assert.Nil(t, got) } }) diff --git a/platforms/adaptors/spibusadaptor.go b/platforms/adaptors/spibusadaptor.go index 55608300a..2672fc9e4 100644 --- a/platforms/adaptors/spibusadaptor.go +++ b/platforms/adaptors/spibusadaptor.go @@ -5,6 +5,7 @@ import ( "sync" multierror "github.com/hashicorp/go-multierror" + "gobot.io/x/gobot/v2/drivers/spi" "gobot.io/x/gobot/v2/system" ) diff --git a/platforms/adaptors/spibusadaptor_test.go b/platforms/adaptors/spibusadaptor_test.go index ac3ca2a07..df4375b62 100644 --- a/platforms/adaptors/spibusadaptor_test.go +++ b/platforms/adaptors/spibusadaptor_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2/drivers/spi" "gobot.io/x/gobot/v2/system" ) @@ -105,7 +106,7 @@ func TestSpiFinalizeWithError(t *testing.T) { // act err := a.Finalize() // assert - assert.Contains(t, err.Error(), "error while SPI close") + require.ErrorContains(t, err, "error while SPI close") } func TestSpiReConnect(t *testing.T) { diff --git a/platforms/audio/audio_adaptor.go b/platforms/audio/audio_adaptor.go index 09d96f931..612eb3b19 100644 --- a/platforms/audio/audio_adaptor.go +++ b/platforms/audio/audio_adaptor.go @@ -41,7 +41,7 @@ func (a *Adaptor) Sound(fileName string) []error { if fileName == "" { log.Println("Requires filename for audio file.") - errorsList = append(errorsList, errors.New("Requires filename for audio file.")) + errorsList = append(errorsList, errors.New("requires filename for audio file")) return errorsList } @@ -74,14 +74,15 @@ func (a *Adaptor) Sound(fileName string) []error { // CommandName defines the playback command for a sound and accepts: // // string: The filename of the audio that needs playback -func CommandName(fileName string) (commandName string, err error) { +func CommandName(fileName string) (string, error) { fileType := path.Ext(fileName) - if fileType == ".mp3" { + switch fileType { + case ".mp3": return "mpg123", nil - } else if fileType == ".wav" { + case ".wav": return "aplay", nil - } else { - return "", errors.New("Unknown filetype for audio file.") + default: + return "", errors.New("unknown filetype for audio file") } } diff --git a/platforms/audio/audio_adaptor_test.go b/platforms/audio/audio_adaptor_test.go index 1545515fe..1e411f8a5 100644 --- a/platforms/audio/audio_adaptor_test.go +++ b/platforms/audio/audio_adaptor_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -41,21 +42,21 @@ func TestAudioAdaptorCommandsMp3(t *testing.T) { func TestAudioAdaptorCommandsUnknown(t *testing.T) { cmd, err := CommandName("whatever.unk") assert.NotEqual(t, "mpg123", cmd) - require.ErrorContains(t, err, "Unknown filetype for audio file.") + require.ErrorContains(t, err, "unknown filetype for audio file") } func TestAudioAdaptorSoundWithNoFilename(t *testing.T) { a := NewAdaptor() errors := a.Sound("") - assert.Equal(t, "Requires filename for audio file.", errors[0].Error()) + require.ErrorContains(t, errors[0], "requires filename for audio file") } func TestAudioAdaptorSoundWithNonexistingFilename(t *testing.T) { a := NewAdaptor() errors := a.Sound("doesnotexist.mp3") - assert.Equal(t, "stat doesnotexist.mp3: no such file or directory", errors[0].Error()) + require.ErrorContains(t, errors[0], "stat doesnotexist.mp3: no such file or directory") } func TestAudioAdaptorSoundWithValidMP3Filename(t *testing.T) { diff --git a/platforms/audio/audio_driver.go b/platforms/audio/audio_driver.go index 8027a3e54..a00dc5cc2 100644 --- a/platforms/audio/audio_driver.go +++ b/platforms/audio/audio_driver.go @@ -53,6 +53,7 @@ func (d *Driver) Connection() gobot.Connection { // // string: The filename of the audio to start playing func (d *Driver) Sound(fileName string) []error { + //nolint:forcetypeassert // ok here return d.Connection().(*Adaptor).Sound(fileName) } @@ -62,11 +63,11 @@ func (d *Driver) Play() []error { } // Start starts the Driver -func (d *Driver) Start() (err error) { - return +func (d *Driver) Start() error { + return nil } // Halt halts the Driver -func (d *Driver) Halt() (err error) { - return +func (d *Driver) Halt() error { + return nil } diff --git a/platforms/audio/audio_driver_test.go b/platforms/audio/audio_driver_test.go index 88c5cde4c..b2efb41ba 100644 --- a/platforms/audio/audio_driver_test.go +++ b/platforms/audio/audio_driver_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -37,7 +38,7 @@ func TestAudioDriverSoundWithNoFilename(t *testing.T) { d := NewDriver(NewAdaptor(), "") errors := d.Sound("") - assert.Equal(t, "Requires filename for audio file.", errors[0].Error()) + require.ErrorContains(t, errors[0], "requires filename for audio file") } func TestAudioDriverSoundWithDefaultFilename(t *testing.T) { diff --git a/platforms/beaglebone/beaglebone_adaptor.go b/platforms/beaglebone/beaglebone_adaptor.go index 2486b9cf2..7048a3c66 100644 --- a/platforms/beaglebone/beaglebone_adaptor.go +++ b/platforms/beaglebone/beaglebone_adaptor.go @@ -8,6 +8,7 @@ import ( "sync" multierror "github.com/hashicorp/go-multierror" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/platforms/adaptors" "gobot.io/x/gobot/v2/system" @@ -140,26 +141,26 @@ func (c *Adaptor) DigitalWrite(id string, val byte) error { } // AnalogRead returns an analog value from specified pin -func (c *Adaptor) AnalogRead(pin string) (val int, err error) { +func (c *Adaptor) AnalogRead(pin string) (int, error) { analogPin, err := c.translateAnalogPin(pin) if err != nil { - return + return 0, err } 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 + return 0, err } buf := make([]byte, 1024) _, err = fi.Read(buf) if err != nil { - return + return 0, err } - val, _ = strconv.Atoi(strings.Split(string(buf), "\n")[0]) - return + val, _ := strconv.Atoi(strings.Split(string(buf), "\n")[0]) + return val, nil } func (c *Adaptor) validateSpiBusNumber(busNr int) error { @@ -218,13 +219,13 @@ func (c *Adaptor) translateAndMuxPWMPin(id string) (string, int, error) { return path, pinInfo.channel, nil } -func (p pwmPinData) findPWMDir(sys *system.Accesser) (dir string, err error) { +func (p pwmPinData) findPWMDir(sys *system.Accesser) (string, error) { items, _ := sys.Find(p.dir, p.dirRegexp) if len(items) == 0 { return "", fmt.Errorf("No path found for PWM directory pattern, '%s' in path '%s'", p.dirRegexp, p.dir) } - dir = items[0] + dir := items[0] info, err := sys.Stat(dir) if err != nil { return "", fmt.Errorf("Error (%v) on access '%s'", err, dir) @@ -233,7 +234,7 @@ func (p pwmPinData) findPWMDir(sys *system.Accesser) (dir string, err error) { return "", fmt.Errorf("The item '%s' is not a directory, which is not expected", dir) } - return + return dir, nil } func (c *Adaptor) muxPin(pin, cmd string) error { diff --git a/platforms/beaglebone/beaglebone_adaptor_test.go b/platforms/beaglebone/beaglebone_adaptor_test.go index f9d03362f..1f5641ba9 100644 --- a/platforms/beaglebone/beaglebone_adaptor_test.go +++ b/platforms/beaglebone/beaglebone_adaptor_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/aio" "gobot.io/x/gobot/v2/drivers/gpio" @@ -172,7 +173,7 @@ func TestAnalogReadFileError(t *testing.T) { a, _ := initTestAdaptorWithMockedFilesystem(mockPaths) _, err := a.AnalogRead("P9_40") - assert.Contains(t, err.Error(), "/sys/bus/iio/devices/iio:device0/in_voltage1_raw: no such file") + require.ErrorContains(t, err, "/sys/bus/iio/devices/iio:device0/in_voltage1_raw: no such file") } func TestDigitalPinDirectionFileError(t *testing.T) { @@ -185,7 +186,7 @@ func TestDigitalPinDirectionFileError(t *testing.T) { a, _ := initTestAdaptorWithMockedFilesystem(mockPaths) err := a.DigitalWrite("P9_12", 1) - assert.Contains(t, err.Error(), "/sys/class/gpio/gpio60/direction: no such file") + require.ErrorContains(t, err, "/sys/class/gpio/gpio60/direction: no such file") // no pin added after previous problem, so no pin to unexport in finalize err = a.Finalize() @@ -206,7 +207,7 @@ func TestDigitalPinFinalizeFileError(t *testing.T) { require.NoError(t, err) err = a.Finalize() - assert.Contains(t, err.Error(), "/sys/class/gpio/unexport: no such file") + require.ErrorContains(t, err, "/sys/class/gpio/unexport: no such file") } func TestPocketName(t *testing.T) { @@ -243,7 +244,7 @@ func TestI2cFinalizeWithErrors(t *testing.T) { // act err = a.Finalize() // assert - assert.Contains(t, err.Error(), "close error") + require.ErrorContains(t, err, "close error") } func Test_validateSpiBusNumber(t *testing.T) { diff --git a/platforms/beaglebone/black_pins.go b/platforms/beaglebone/black_pins.go index e6e877770..9d8357f46 100644 --- a/platforms/beaglebone/black_pins.go +++ b/platforms/beaglebone/black_pins.go @@ -50,14 +50,27 @@ var bbbPinMap = map[string]int{ } var bbbPwmPinMap = map[string]pwmPinData{ - "P8_13": {dir: "/sys/devices/platform/ocp/48304000.epwmss/48304200.pwm/pwm/", dirRegexp: "pwmchip[0-9]+$", channel: 1}, - "P8_19": {dir: "/sys/devices/platform/ocp/48304000.epwmss/48304200.pwm/pwm/", dirRegexp: "pwmchip[0-9]+$", channel: 0}, - - "P9_14": {dir: "/sys/devices/platform/ocp/48302000.epwmss/48302200.pwm/pwm/", dirRegexp: "pwmchip[0-9]+$", channel: 0}, - "P9_16": {dir: "/sys/devices/platform/ocp/48302000.epwmss/48302200.pwm/pwm/", dirRegexp: "pwmchip[0-9]+$", channel: 1}, - "P9_21": {dir: "/sys/devices/platform/ocp/48300000.epwmss/48300200.pwm/pwm/", dirRegexp: "pwmchip[0-9]+$", channel: 1}, - "P9_22": {dir: "/sys/devices/platform/ocp/48300000.epwmss/48300200.pwm/pwm/", dirRegexp: "pwmchip[0-9]+$", channel: 0}, - "P9_42": {dir: "/sys/devices/platform/ocp/48300000.epwmss/48300100.ecap/pwm/", dirRegexp: "pwmchip[0-9]+$", channel: 0}, + "P8_13": { + dir: "/sys/devices/platform/ocp/48304000.epwmss/48304200.pwm/pwm/", dirRegexp: "pwmchip[0-9]+$", channel: 1, + }, + "P8_19": { + dir: "/sys/devices/platform/ocp/48304000.epwmss/48304200.pwm/pwm/", dirRegexp: "pwmchip[0-9]+$", channel: 0, + }, + "P9_14": { + dir: "/sys/devices/platform/ocp/48302000.epwmss/48302200.pwm/pwm/", dirRegexp: "pwmchip[0-9]+$", channel: 0, + }, + "P9_16": { + dir: "/sys/devices/platform/ocp/48302000.epwmss/48302200.pwm/pwm/", dirRegexp: "pwmchip[0-9]+$", channel: 1, + }, + "P9_21": { + dir: "/sys/devices/platform/ocp/48300000.epwmss/48300200.pwm/pwm/", dirRegexp: "pwmchip[0-9]+$", channel: 1, + }, + "P9_22": { + dir: "/sys/devices/platform/ocp/48300000.epwmss/48300200.pwm/pwm/", dirRegexp: "pwmchip[0-9]+$", channel: 0, + }, + "P9_42": { + dir: "/sys/devices/platform/ocp/48300000.epwmss/48300100.ecap/pwm/", dirRegexp: "pwmchip[0-9]+$", channel: 0, + }, } var bbbAnalogPinMap = map[string]string{ diff --git a/platforms/ble/battery_driver.go b/platforms/ble/battery_driver.go index fc38e7262..4b3e59628 100644 --- a/platforms/ble/battery_driver.go +++ b/platforms/ble/battery_driver.go @@ -36,27 +36,25 @@ func (b *BatteryDriver) SetName(n string) { b.name = n } // adaptor returns BLE adaptor func (b *BatteryDriver) adaptor() BLEConnector { + //nolint:forcetypeassert // ok here return b.Connection().(BLEConnector) } // Start tells driver to get ready to do work -func (b *BatteryDriver) Start() (err error) { - return -} +func (b *BatteryDriver) Start() error { return nil } // Halt stops battery driver (void) -func (b *BatteryDriver) Halt() (err error) { return } +func (b *BatteryDriver) Halt() error { return nil } // GetBatteryLevel reads and returns the current battery level -func (b *BatteryDriver) GetBatteryLevel() (level uint8) { - var l uint8 +func (b *BatteryDriver) GetBatteryLevel() uint8 { c, err := b.adaptor().ReadCharacteristic("2a19") if err != nil { log.Println(err) - return + return 0 } buf := bytes.NewBuffer(c) val, _ := buf.ReadByte() - l = val - return l + level := val + return level } diff --git a/platforms/ble/battery_driver_test.go b/platforms/ble/battery_driver_test.go index 70ee9d133..84e671f70 100644 --- a/platforms/ble/battery_driver_test.go +++ b/platforms/ble/battery_driver_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/ble/ble_client_adaptor.go b/platforms/ble/ble_client_adaptor.go index d3a270e0a..8273e1c94 100644 --- a/platforms/ble/ble_client_adaptor.go +++ b/platforms/ble/ble_client_adaptor.go @@ -6,9 +6,9 @@ import ( "sync" "time" - "gobot.io/x/gobot/v2" - "tinygo.org/x/bluetooth" + + "gobot.io/x/gobot/v2" ) var ( @@ -154,7 +154,7 @@ func (b *ClientAdaptor) Finalize() error { // ReadCharacteristic returns bytes from the BLE device for the // requested characteristic uuid -func (b *ClientAdaptor) ReadCharacteristic(cUUID string) (data []byte, err error) { +func (b *ClientAdaptor) ReadCharacteristic(cUUID string) ([]byte, error) { if !b.connected { return nil, fmt.Errorf("Cannot read from BLE device until connected") } diff --git a/platforms/ble/ble_client_adaptor_test.go b/platforms/ble/ble_client_adaptor_test.go index 96fb233f1..0862405e8 100644 --- a/platforms/ble/ble_client_adaptor_test.go +++ b/platforms/ble/ble_client_adaptor_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/ble/device_information_driver.go b/platforms/ble/device_information_driver.go index 0629a21db..79710a9df 100644 --- a/platforms/ble/device_information_driver.go +++ b/platforms/ble/device_information_driver.go @@ -36,35 +36,34 @@ func (b *DeviceInformationDriver) SetName(n string) { b.name = n } // adaptor returns BLE adaptor for this device func (b *DeviceInformationDriver) adaptor() BLEConnector { + //nolint:forcetypeassert // ok here return b.Connection().(BLEConnector) } // Start tells driver to get ready to do work -func (b *DeviceInformationDriver) Start() (err error) { - return -} +func (b *DeviceInformationDriver) Start() error { return nil } // Halt stops driver (void) -func (b *DeviceInformationDriver) Halt() (err error) { return } +func (b *DeviceInformationDriver) Halt() error { return nil } // GetModelNumber returns the model number for the BLE Peripheral -func (b *DeviceInformationDriver) GetModelNumber() (model string) { +func (b *DeviceInformationDriver) GetModelNumber() string { c, err := b.adaptor().ReadCharacteristic("2a24") if err != nil { log.Println(err) - return + return "" } buf := bytes.NewBuffer(c) - model = buf.String() - return + model := buf.String() + return model } // GetFirmwareRevision returns the firmware revision for the BLE Peripheral -func (b *DeviceInformationDriver) GetFirmwareRevision() (revision string) { +func (b *DeviceInformationDriver) GetFirmwareRevision() string { c, err := b.adaptor().ReadCharacteristic("2a26") if err != nil { log.Println(err) - return + return "" } buf := bytes.NewBuffer(c) val := buf.String() @@ -72,11 +71,11 @@ func (b *DeviceInformationDriver) GetFirmwareRevision() (revision string) { } // GetHardwareRevision returns the hardware revision for the BLE Peripheral -func (b *DeviceInformationDriver) GetHardwareRevision() (revision string) { +func (b *DeviceInformationDriver) GetHardwareRevision() string { c, err := b.adaptor().ReadCharacteristic("2a27") if err != nil { log.Println(err) - return + return "" } buf := bytes.NewBuffer(c) val := buf.String() @@ -84,11 +83,11 @@ func (b *DeviceInformationDriver) GetHardwareRevision() (revision string) { } // GetManufacturerName returns the manufacturer name for the BLE Peripheral -func (b *DeviceInformationDriver) GetManufacturerName() (manufacturer string) { +func (b *DeviceInformationDriver) GetManufacturerName() string { c, err := b.adaptor().ReadCharacteristic("2a29") if err != nil { log.Println(err) - return + return "" } buf := bytes.NewBuffer(c) val := buf.String() @@ -96,11 +95,11 @@ func (b *DeviceInformationDriver) GetManufacturerName() (manufacturer string) { } // GetPnPId returns the PnP ID for the BLE Peripheral -func (b *DeviceInformationDriver) GetPnPId() (model string) { +func (b *DeviceInformationDriver) GetPnPId() string { c, err := b.adaptor().ReadCharacteristic("2a50") if err != nil { log.Println(err) - return + return "" } buf := bytes.NewBuffer(c) val := buf.String() diff --git a/platforms/ble/device_information_driver_test.go b/platforms/ble/device_information_driver_test.go index 72b14a908..1835ce8d1 100644 --- a/platforms/ble/device_information_driver_test.go +++ b/platforms/ble/device_information_driver_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/ble/generic_access_driver.go b/platforms/ble/generic_access_driver.go index 7e4f9d59f..3b3f40c08 100644 --- a/platforms/ble/generic_access_driver.go +++ b/platforms/ble/generic_access_driver.go @@ -37,6 +37,7 @@ func (b *GenericAccessDriver) SetName(n string) { b.name = n } // adaptor returns BLE adaptor for this device func (b *GenericAccessDriver) adaptor() BLEConnector { + //nolint:forcetypeassert // ok here return b.Connection().(BLEConnector) } diff --git a/platforms/ble/generic_access_driver_test.go b/platforms/ble/generic_access_driver_test.go index 9b09d6435..c32b3384e 100644 --- a/platforms/ble/generic_access_driver_test.go +++ b/platforms/ble/generic_access_driver_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/ble/helpers_test.go b/platforms/ble/helpers_test.go index 7df468b72..dfcd7e36d 100644 --- a/platforms/ble/helpers_test.go +++ b/platforms/ble/helpers_test.go @@ -14,30 +14,30 @@ type bleTestClientAdaptor struct { testWriteCharacteristic func(string, []byte) error } -func (t *bleTestClientAdaptor) Connect() (err error) { return } -func (t *bleTestClientAdaptor) Reconnect() (err error) { return } -func (t *bleTestClientAdaptor) Disconnect() (err error) { return } -func (t *bleTestClientAdaptor) Finalize() (err error) { return } +func (t *bleTestClientAdaptor) Connect() error { return nil } +func (t *bleTestClientAdaptor) Reconnect() error { return nil } +func (t *bleTestClientAdaptor) Disconnect() error { return nil } +func (t *bleTestClientAdaptor) Finalize() error { return nil } func (t *bleTestClientAdaptor) Name() string { return t.name } func (t *bleTestClientAdaptor) SetName(n string) { t.name = n } func (t *bleTestClientAdaptor) Address() string { return t.address } func (t *bleTestClientAdaptor) WithoutResponses(use bool) { t.withoutResponses = use } -func (t *bleTestClientAdaptor) ReadCharacteristic(cUUID string) (data []byte, err error) { +func (t *bleTestClientAdaptor) ReadCharacteristic(cUUID string) ([]byte, error) { t.mtx.Lock() defer t.mtx.Unlock() return t.testReadCharacteristic(cUUID) } -func (t *bleTestClientAdaptor) WriteCharacteristic(cUUID string, data []byte) (err error) { +func (t *bleTestClientAdaptor) WriteCharacteristic(cUUID string, data []byte) error { t.mtx.Lock() defer t.mtx.Unlock() return t.testWriteCharacteristic(cUUID, data) } -func (t *bleTestClientAdaptor) Subscribe(cUUID string, f func([]byte, error)) (err error) { +func (t *bleTestClientAdaptor) Subscribe(cUUID string, f func([]byte, error)) error { // TODO: implement this... - return + return nil } func (t *bleTestClientAdaptor) TestReadCharacteristic(f func(cUUID string) (data []byte, err error)) { @@ -46,7 +46,7 @@ func (t *bleTestClientAdaptor) TestReadCharacteristic(f func(cUUID string) (data t.testReadCharacteristic = f } -func (t *bleTestClientAdaptor) TestWriteCharacteristic(f func(cUUID string, data []byte) (err error)) { +func (t *bleTestClientAdaptor) TestWriteCharacteristic(f func(cUUID string, data []byte) error) { t.mtx.Lock() defer t.mtx.Unlock() t.testWriteCharacteristic = f @@ -55,11 +55,11 @@ func (t *bleTestClientAdaptor) TestWriteCharacteristic(f func(cUUID string, data func NewBleTestAdaptor() *bleTestClientAdaptor { return &bleTestClientAdaptor{ address: "01:02:03:04:05:06", - testReadCharacteristic: func(cUUID string) (data []byte, e error) { - return + testReadCharacteristic: func(cUUID string) ([]byte, error) { + return []byte{}, nil }, - testWriteCharacteristic: func(cUUID string, data []byte) (e error) { - return + testWriteCharacteristic: func(cUUID string, data []byte) error { + return nil }, } } diff --git a/platforms/ble/serial_port.go b/platforms/ble/serial_port.go index db6307591..4cbfedbe6 100644 --- a/platforms/ble/serial_port.go +++ b/platforms/ble/serial_port.go @@ -37,13 +37,13 @@ func (p *SerialPort) Open() error { } // Read reads bytes from BLE serial port connection -func (p *SerialPort) Read(b []byte) (n int, err error) { +func (p *SerialPort) Read(b []byte) (int, error) { if len(p.responseData) == 0 { - return + return 0, nil } p.responseMutex.Lock() - n = len(b) + n := len(b) if len(p.responseData) < n { n = len(p.responseData) } @@ -56,14 +56,14 @@ func (p *SerialPort) Read(b []byte) (n int, err error) { } p.responseMutex.Unlock() - return + return n, nil } // Write writes to the BLE serial port connection -func (p *SerialPort) Write(b []byte) (n int, err error) { - err = p.client.WriteCharacteristic(p.tid, b) - n = len(b) - return +func (p *SerialPort) Write(b []byte) (int, error) { + err := p.client.WriteCharacteristic(p.tid, b) + n := len(b) + return n, err } // Close closes the BLE serial port connection diff --git a/platforms/chip/chip_adaptor.go b/platforms/chip/chip_adaptor.go index 4cc9eda5f..c7dd3a21a 100644 --- a/platforms/chip/chip_adaptor.go +++ b/platforms/chip/chip_adaptor.go @@ -9,6 +9,7 @@ import ( "sync" multierror "github.com/hashicorp/go-multierror" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/platforms/adaptors" "gobot.io/x/gobot/v2/system" @@ -108,14 +109,14 @@ func (c *Adaptor) Finalize() error { return err } -func getXIOBase() (baseAddr int, err error) { +func getXIOBase() (int, error) { // Default to original base from 4.3 kernel - baseAddr = 408 + baseAddr := 408 const expanderID = "pcf8574a" labels, err := filepath.Glob("/sys/class/gpio/*/label") if err != nil { - return + return baseAddr, err } for _, labelPath := range labels { diff --git a/platforms/chip/chip_adaptor_test.go b/platforms/chip/chip_adaptor_test.go index f8dc92ee2..d319119d6 100644 --- a/platforms/chip/chip_adaptor_test.go +++ b/platforms/chip/chip_adaptor_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/gpio" "gobot.io/x/gobot/v2/drivers/i2c" @@ -78,7 +79,7 @@ func TestFinalizeErrorAfterGPIO(t *testing.T) { fs.WithWriteError = true err := a.Finalize() - assert.Contains(t, err.Error(), "write error") + require.ErrorContains(t, err, "write error") } func TestFinalizeErrorAfterPWM(t *testing.T) { @@ -92,7 +93,7 @@ func TestFinalizeErrorAfterPWM(t *testing.T) { fs.WithWriteError = true err := a.Finalize() - assert.Contains(t, err.Error(), "write error") + require.ErrorContains(t, err, "write error") } func TestDigitalIO(t *testing.T) { @@ -175,7 +176,7 @@ func TestI2cFinalizeWithErrors(t *testing.T) { // act err = a.Finalize() // assert - assert.Contains(t, err.Error(), "close error") + require.ErrorContains(t, err, "close error") } func Test_validateI2cBusNumber(t *testing.T) { diff --git a/platforms/dexter/gopigo3/driver.go b/platforms/dexter/gopigo3/driver.go index f4c3f12ad..0edbdb1d2 100644 --- a/platforms/dexter/gopigo3/driver.go +++ b/platforms/dexter/gopigo3/driver.go @@ -8,10 +8,12 @@ import ( "bytes" "encoding/binary" "fmt" + "log" "math" "time" "github.com/hashicorp/go-multierror" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/spi" ) @@ -66,15 +68,22 @@ const ( ) const ( - WHEEL_BASE_WIDTH = 117 // distance (mm) from left wheel to right wheel. This works with the initial GPG3 prototype. Will need to be adjusted. - WHEEL_DIAMETER = 66.5 // wheel diameter (mm) - WHEEL_BASE_CIRCUMFERENCE = WHEEL_BASE_WIDTH * math.Pi // circumference of the circle the wheels will trace while turning (mm) - WHEEL_CIRCUMFERENCE = WHEEL_DIAMETER * math.Pi // circumference of the wheels (mm) - MOTOR_GEAR_RATIO = 120 // motor gear ratio - ENCODER_TICKS_PER_ROTATION = 6 // encoder ticks per motor rotation (number of magnet positions) - MOTOR_TICKS_PER_DEGREE = ((MOTOR_GEAR_RATIO * ENCODER_TICKS_PER_ROTATION) / 360.0) // encoder ticks per output shaft rotation degree - GROVE_I2C_LENGTH_LIMIT = 16 - MOTOR_FLOAT = -128 + // distance (mm) from left wheel to right wheel. This works with the initial GPG3 prototype. Will need to be adjusted. + WHEEL_BASE_WIDTH = 117 + // wheel diameter (mm) + WHEEL_DIAMETER = 66.5 + // circumference of the circle the wheels will trace while turning (mm) + WHEEL_BASE_CIRCUMFERENCE = WHEEL_BASE_WIDTH * math.Pi + // circumference of the wheels (mm) + WHEEL_CIRCUMFERENCE = WHEEL_DIAMETER * math.Pi + // motor gear ratio + MOTOR_GEAR_RATIO = 120 + // encoder ticks per motor rotation (number of magnet positions) + ENCODER_TICKS_PER_ROTATION = 6 + // encoder ticks per output shaft rotation degree + MOTOR_TICKS_PER_DEGREE = ((MOTOR_GEAR_RATIO * ENCODER_TICKS_PER_ROTATION) / 360.0) + GROVE_I2C_LENGTH_LIMIT = 16 + MOTOR_FLOAT = -128 ) // GroveMode sets the mode of AD pins on the gopigo3. @@ -182,55 +191,62 @@ func NewDriver(a spi.Connector, options ...func(spi.Config)) *Driver { // use /dev/spidev0.1 spiConfig.SetBusNumber(0) spiConfig.SetChipNumber(1) - g := &Driver{ + d := &Driver{ name: gobot.DefaultName("GoPiGo3"), connector: a, Config: spiConfig, } for _, option := range options { - option(g) + option(d) } - return g + return d } // Name returns the name of the device. -func (g *Driver) Name() string { return g.name } +func (d *Driver) Name() string { return d.name } // SetName sets the name of the device. -func (g *Driver) SetName(n string) { g.name = n } +func (d *Driver) SetName(n string) { d.name = n } // Connection returns the Connection of the device. -func (g *Driver) Connection() gobot.Connection { return g.connection.(gobot.Connection) } +func (d *Driver) Connection() gobot.Connection { + if conn, ok := d.connection.(gobot.Connection); ok { + return conn + } + + log.Printf("%s has no gobot connection\n", d.name) + return nil +} // Halt stops the driver. -func (g *Driver) Halt() error { - err := g.resetAll() +func (d *Driver) Halt() error { + err := d.resetAll() time.Sleep(10 * time.Millisecond) return err } // Start initializes the GoPiGo3 -func (g *Driver) Start() error { - bus := g.GetBusNumberOrDefault(g.connector.SpiDefaultBusNumber()) - chip := g.GetChipNumberOrDefault(g.connector.SpiDefaultChipNumber()) - mode := g.GetModeOrDefault(g.connector.SpiDefaultMode()) - bits := g.GetBitCountOrDefault(g.connector.SpiDefaultBitCount()) - maxSpeed := g.GetSpeedOrDefault(g.connector.SpiDefaultMaxSpeed()) +func (d *Driver) Start() error { + bus := d.GetBusNumberOrDefault(d.connector.SpiDefaultBusNumber()) + chip := d.GetChipNumberOrDefault(d.connector.SpiDefaultChipNumber()) + mode := d.GetModeOrDefault(d.connector.SpiDefaultMode()) + bits := d.GetBitCountOrDefault(d.connector.SpiDefaultBitCount()) + maxSpeed := d.GetSpeedOrDefault(d.connector.SpiDefaultMaxSpeed()) var err error - g.connection, err = g.connector.GetSpiConnection(bus, chip, mode, bits, maxSpeed) + d.connection, err = d.connector.GetSpiConnection(bus, chip, mode, bits, maxSpeed) return err } // GetManufacturerName returns the manufacturer from the firmware. -func (g *Driver) GetManufacturerName() (mName string, err error) { +func (d *Driver) GetManufacturerName() (string, error) { // read 24 bytes to get manufacturer name - response, err := g.readBytes(goPiGo3Address, GET_MANUFACTURER, 24) + response, err := d.readBytes(goPiGo3Address, GET_MANUFACTURER, 24) if err != nil { - return mName, err + return "", err } - if err := g.responseValid(response); err != nil { - return mName, err + if err := d.responseValid(response); err != nil { + return "", err } mf := response[4:23] mf = bytes.Trim(mf, "\x00") @@ -238,14 +254,14 @@ func (g *Driver) GetManufacturerName() (mName string, err error) { } // GetBoardName returns the board name from the firmware. -func (g *Driver) GetBoardName() (bName string, err error) { +func (d *Driver) GetBoardName() (string, error) { // read 24 bytes to get board name - response, err := g.readBytes(goPiGo3Address, GET_NAME, 24) + response, err := d.readBytes(goPiGo3Address, GET_NAME, 24) if err != nil { - return bName, err + return "", err } - if err := g.responseValid(response); err != nil { - return bName, err + if err := d.responseValid(response); err != nil { + return "", err } mf := response[4:23] mf = bytes.Trim(mf, "\x00") @@ -253,10 +269,10 @@ func (g *Driver) GetBoardName() (bName string, err error) { } // GetHardwareVersion returns the hardware version from the firmware. -func (g *Driver) GetHardwareVersion() (hVer string, err error) { - response, err := g.readUint32(goPiGo3Address, GET_HARDWARE_VERSION) +func (d *Driver) GetHardwareVersion() (string, error) { + response, err := d.readUint32(goPiGo3Address, GET_HARDWARE_VERSION) if err != nil { - return hVer, err + return "", err } major := response / 1000000 minor := response / 1000 % 1000 @@ -265,10 +281,10 @@ func (g *Driver) GetHardwareVersion() (hVer string, err error) { } // GetFirmwareVersion returns the current firmware version. -func (g *Driver) GetFirmwareVersion() (fVer string, err error) { - response, err := g.readUint32(goPiGo3Address, GET_FIRMWARE_VERSION) +func (d *Driver) GetFirmwareVersion() (string, error) { + response, err := d.readUint32(goPiGo3Address, GET_FIRMWARE_VERSION) if err != nil { - return fVer, err + return "", err } major := response / 1000000 minor := response / 1000 % 1000 @@ -277,33 +293,35 @@ func (g *Driver) GetFirmwareVersion() (fVer string, err error) { } // GetSerialNumber returns the 128-bit hardware serial number of the board. -func (g *Driver) GetSerialNumber() (sNum string, err error) { +func (d *Driver) GetSerialNumber() (string, error) { // read 20 bytes to get the serial number - response, err := g.readBytes(goPiGo3Address, GET_ID, 20) + response, err := d.readBytes(goPiGo3Address, GET_ID, 20) if err != nil { - return sNum, err + return "", err } - if err := g.responseValid(response); err != nil { - return sNum, err + if err := d.responseValid(response); err != nil { + return "", err } - return fmt.Sprintf("%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", response[4], response[5], response[6], response[7], response[8], response[9], response[10], response[11], response[12], response[13], response[14], response[15], response[16], response[17], response[18], response[19]), nil + return fmt.Sprintf("%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", response[4], response[5], + response[6], response[7], response[8], response[9], response[10], response[11], response[12], response[13], + response[14], response[15], response[16], response[17], response[18], response[19]), nil } // Get5vVoltage returns the current voltage on the 5v line. -func (g *Driver) Get5vVoltage() (voltage float32, err error) { - val, err := g.readUint16(goPiGo3Address, GET_VOLTAGE_5V) +func (d *Driver) Get5vVoltage() (float32, error) { + val, err := d.readUint16(goPiGo3Address, GET_VOLTAGE_5V) return (float32(val) / 1000.0), err } // GetBatteryVoltage gets the battery voltage from the main battery pack (7v-12v). -func (g *Driver) GetBatteryVoltage() (voltage float32, err error) { - val, err := g.readUint16(goPiGo3Address, GET_VOLTAGE_VCC) +func (d *Driver) GetBatteryVoltage() (float32, error) { + val, err := d.readUint16(goPiGo3Address, GET_VOLTAGE_VCC) return (float32(val) / 1000.0), err } // SetLED sets rgb values from 0 to 255. -func (g *Driver) SetLED(led Led, red, green, blue uint8) error { - return g.writeBytes([]byte{ +func (d *Driver) SetLED(led Led, red, green, blue uint8) error { + return d.writeBytes([]byte{ goPiGo3Address, SET_LED, byte(led), @@ -314,8 +332,8 @@ func (g *Driver) SetLED(led Led, red, green, blue uint8) error { } // SetServo sets a servo's position in microseconds (0-16666). -func (g *Driver) SetServo(srvo Servo, us uint16) error { - return g.writeBytes([]byte{ +func (d *Driver) SetServo(srvo Servo, us uint16) error { + return d.writeBytes([]byte{ goPiGo3Address, SET_SERVO, byte(srvo), @@ -326,7 +344,7 @@ func (g *Driver) SetServo(srvo Servo, us uint16) error { // ServoWrite writes an angle (0-180) to the given servo (servo 1 or servo 2). // Must implement the ServoWriter interface of gpio package. -func (g *Driver) ServoWrite(port string, angle byte) error { +func (d *Driver) ServoWrite(port string, angle byte) error { srvo := SERVO_1 // default for unknown ports if port == "2" || port == "SERVO_2" { srvo = SERVO_2 @@ -337,12 +355,12 @@ func (g *Driver) ServoWrite(port string, angle byte) error { angle = 180 } pulseWidth := ((1500 - (pulseWidthRange / 2)) + ((pulseWidthRange / 180) * int(angle))) - return g.SetServo(srvo, uint16(pulseWidth)) + return d.SetServo(srvo, uint16(pulseWidth)) } // SetMotorPower sets a motor's power from -128 to 127. -func (g *Driver) SetMotorPower(motor Motor, power int8) error { - return g.writeBytes([]byte{ +func (d *Driver) SetMotorPower(motor Motor, power int8) error { + return d.writeBytes([]byte{ goPiGo3Address, SET_MOTOR_PWM, byte(motor), @@ -351,9 +369,9 @@ func (g *Driver) SetMotorPower(motor Motor, power int8) error { } // SetMotorPosition sets the motor's position in degrees. -func (g *Driver) SetMotorPosition(motor Motor, position int) error { +func (d *Driver) SetMotorPosition(motor Motor, position int) error { positionRaw := position * MOTOR_TICKS_PER_DEGREE - return g.writeBytes([]byte{ + return d.writeBytes([]byte{ goPiGo3Address, SET_MOTOR_POSITION, byte(motor), @@ -365,21 +383,21 @@ func (g *Driver) SetMotorPosition(motor Motor, position int) error { } // SetMotorDps sets the motor target speed in degrees per second. -func (g *Driver) SetMotorDps(motor Motor, dps int) error { - d := dps * MOTOR_TICKS_PER_DEGREE - return g.writeBytes([]byte{ +func (d *Driver) SetMotorDps(motor Motor, dps int) error { + mdps := dps * MOTOR_TICKS_PER_DEGREE + return d.writeBytes([]byte{ goPiGo3Address, SET_MOTOR_DPS, byte(motor), - byte((d >> 8) & 0xFF), - byte(d & 0xFF), + byte((mdps >> 8) & 0xFF), + byte(mdps & 0xFF), }) } // SetMotorLimits sets the speed limits for a motor. -func (g *Driver) SetMotorLimits(motor Motor, power int8, dps int) error { +func (d *Driver) SetMotorLimits(motor Motor, power int8, dps int) error { dpsUint := dps * MOTOR_TICKS_PER_DEGREE - return g.writeBytes([]byte{ + return d.writeBytes([]byte{ goPiGo3Address, SET_MOTOR_LIMITS, byte(motor), @@ -390,16 +408,18 @@ func (g *Driver) SetMotorLimits(motor Motor, power int8, dps int) error { } // GetMotorStatus returns the status for the given motor. -func (g *Driver) GetMotorStatus(motor Motor) (flags uint8, power uint16, encoder, dps int, err error) { +// +//nolint:nonamedreturns // sufficient here +func (d *Driver) GetMotorStatus(motor Motor) (flags uint8, power uint16, encoder, dps int, err error) { message := GET_MOTOR_STATUS_RIGHT if motor == MOTOR_LEFT { message = GET_MOTOR_STATUS_LEFT } - response, err := g.readBytes(goPiGo3Address, message, 12) + response, err := d.readBytes(goPiGo3Address, message, 12) if err != nil { return flags, power, encoder, dps, err } - if err := g.responseValid(response); err != nil { + if err := d.responseValid(response); err != nil { return flags, power, encoder, dps, err } // get flags @@ -421,10 +441,10 @@ func (g *Driver) GetMotorStatus(motor Motor) (flags uint8, power uint16, encoder encoder = int(uint64(e) - 0x100000000) } // get dps - d := make([]byte, 4) - d[1] = response[10] - d[0] = response[11] - ds := binary.LittleEndian.Uint32(d) + dpsRaw := make([]byte, 4) + dpsRaw[1] = response[10] + dpsRaw[0] = response[11] + ds := binary.LittleEndian.Uint32(dpsRaw) dps = int(ds) if ds&0x8000 == 0x8000 { dps = int(ds - 0x10000) @@ -433,16 +453,16 @@ func (g *Driver) GetMotorStatus(motor Motor) (flags uint8, power uint16, encoder } // GetMotorEncoder reads a motor's encoder in degrees. -func (g *Driver) GetMotorEncoder(motor Motor) (encoder int64, err error) { +func (d *Driver) GetMotorEncoder(motor Motor) (int64, error) { message := GET_MOTOR_ENCODER_RIGHT if motor == MOTOR_LEFT { message = GET_MOTOR_ENCODER_LEFT } - response, err := g.readUint32(goPiGo3Address, message) + response, err := d.readUint32(goPiGo3Address, message) if err != nil { - return encoder, err + return 0, err } - encoder = int64(response) + encoder := int64(response) if response&0x80000000 != 0 { encoder = encoder - 0x100000000 } @@ -451,9 +471,9 @@ func (g *Driver) GetMotorEncoder(motor Motor) (encoder int64, err error) { } // OffsetMotorEncoder offsets a motor's encoder for calibration purposes. -func (g *Driver) OffsetMotorEncoder(motor Motor, offset float64) error { +func (d *Driver) OffsetMotorEncoder(motor Motor, offset float64) error { offsetUint := math.Float64bits(offset * MOTOR_TICKS_PER_DEGREE) - return g.writeBytes([]byte{ + return d.writeBytes([]byte{ goPiGo3Address, OFFSET_MOTOR_ENCODER, byte(motor), @@ -465,8 +485,8 @@ func (g *Driver) OffsetMotorEncoder(motor Motor, offset float64) error { } // SetGroveType sets the given port to a grove device type. -func (g *Driver) SetGroveType(port Grove, gType GroveType) error { - return g.writeBytes([]byte{ +func (d *Driver) SetGroveType(port Grove, gType GroveType) error { + return d.writeBytes([]byte{ goPiGo3Address, SET_GROVE_TYPE, byte(port), @@ -475,8 +495,8 @@ func (g *Driver) SetGroveType(port Grove, gType GroveType) error { } // SetGroveMode sets the mode a given pin/port of the grove connector. -func (g *Driver) SetGroveMode(port Grove, mode GroveMode) error { - return g.writeBytes([]byte{ +func (d *Driver) SetGroveMode(port Grove, mode GroveMode) error { + return d.writeBytes([]byte{ goPiGo3Address, SET_GROVE_MODE, byte(port), @@ -485,12 +505,12 @@ func (g *Driver) SetGroveMode(port Grove, mode GroveMode) error { } // SetPWMDuty sets the pwm duty cycle for the given pin/port. -func (g *Driver) SetPWMDuty(port Grove, duty uint16) error { +func (d *Driver) SetPWMDuty(port Grove, duty uint16) error { if duty > 100 { duty = 100 } duty = duty * 10 - return g.writeBytes([]byte{ + return d.writeBytes([]byte{ goPiGo3Address, SET_GROVE_PWM_DUTY, byte(port), @@ -500,14 +520,14 @@ func (g *Driver) SetPWMDuty(port Grove, duty uint16) error { } // SetPWMFreq setst the pwm frequency for the given pin/port. -func (g *Driver) SetPWMFreq(port Grove, freq uint16) error { +func (d *Driver) SetPWMFreq(port Grove, freq uint16) error { if freq < 3 { freq = 3 } if freq > 48000 { freq = 48000 } - return g.writeBytes([]byte{ + return d.writeBytes([]byte{ goPiGo3Address, SET_GROVE_PWM_FREQUENCY, byte(port), @@ -517,7 +537,7 @@ func (g *Driver) SetPWMFreq(port Grove, freq uint16) error { } // PwmWrite implents the pwm interface for the gopigo3. -func (g *Driver) PwmWrite(pin string, val byte) error { +func (d *Driver) PwmWrite(pin string, val byte) error { var ( grovePin, grovePort Grove err error @@ -525,49 +545,45 @@ func (g *Driver) PwmWrite(pin string, val byte) error { if grovePin, grovePort, _, _, err = getGroveAddresses(pin); err != nil { return err } - if err := g.SetGroveType(grovePort, CUSTOM); err != nil { + if err := d.SetGroveType(grovePort, CUSTOM); err != nil { return err } time.Sleep(10 * time.Millisecond) - if err = g.SetGroveMode(grovePin, GROVE_OUTPUT_PWM); err != nil { + if err = d.SetGroveMode(grovePin, GROVE_OUTPUT_PWM); err != nil { return err } time.Sleep(10 * time.Millisecond) - if err = g.SetPWMFreq(grovePin, 24000); err != nil { + if err = d.SetPWMFreq(grovePin, 24000); err != nil { return err } val64 := math.Float64frombits(uint64(val)) dutyCycle := uint16(math.Float64bits((100.0 / 255.0) * val64)) - return g.SetPWMDuty(grovePin, dutyCycle) + return d.SetPWMDuty(grovePin, dutyCycle) } // AnalogRead returns the analog value of the given pin. -func (g *Driver) AnalogRead(pin string) (value int, err error) { - var ( - grovePin, grovePort Grove - analogCmd byte - ) - grovePin, grovePort, analogCmd, _, err = getGroveAddresses(pin) +func (d *Driver) AnalogRead(pin string) (int, error) { + grovePin, grovePort, analogCmd, _, err := getGroveAddresses(pin) if err != nil { - return value, err + return 0, err } - if err := g.SetGroveType(grovePort, CUSTOM); err != nil { - return value, err + if err := d.SetGroveType(grovePort, CUSTOM); err != nil { + return 0, err } time.Sleep(10 * time.Millisecond) - if err := g.SetGroveMode(grovePin, GROVE_INPUT_ANALOG); err != nil { - return value, err + if err := d.SetGroveMode(grovePin, GROVE_INPUT_ANALOG); err != nil { + return 0, err } time.Sleep(10 * time.Millisecond) - response, err := g.readBytes(goPiGo3Address, analogCmd, 7) + response, err := d.readBytes(goPiGo3Address, analogCmd, 7) if err != nil { - return value, err + return 0, err } - if err := g.responseValid(response); err != nil { - return value, err + if err := d.responseValid(response); err != nil { + return 0, err } - if err := g.valueValid(response); err != nil { - return value, err + if err := d.valueValid(response); err != nil { + return 0, err } highBytes := uint16(response[5]) lowBytes := uint16(response[6]) @@ -575,7 +591,7 @@ func (g *Driver) AnalogRead(pin string) (value int, err error) { } // DigitalWrite writes a 0/1 value to the given pin. -func (g *Driver) DigitalWrite(pin string, val byte) error { +func (d *Driver) DigitalWrite(pin string, val byte) error { var ( grovePin, grovePort Grove err error @@ -584,15 +600,15 @@ func (g *Driver) DigitalWrite(pin string, val byte) error { if err != nil { return err } - if err := g.SetGroveType(grovePort, CUSTOM); err != nil { + if err := d.SetGroveType(grovePort, CUSTOM); err != nil { return err } time.Sleep(10 * time.Millisecond) - if err := g.SetGroveMode(grovePin, GROVE_OUTPUT_DIGITAL); err != nil { + if err := d.SetGroveMode(grovePin, GROVE_OUTPUT_DIGITAL); err != nil { return err } time.Sleep(10 * time.Millisecond) - return g.writeBytes([]byte{ + return d.writeBytes([]byte{ goPiGo3Address, SET_GROVE_STATE, byte(grovePin), @@ -601,38 +617,35 @@ func (g *Driver) DigitalWrite(pin string, val byte) error { } // DigitalRead reads the 0/1 value from the given pin. -func (g *Driver) DigitalRead(pin string) (value int, err error) { - var ( - grovePin, grovePort Grove - stateCmd byte - ) - grovePin, grovePort, _, stateCmd, err = getGroveAddresses(pin) +func (d *Driver) DigitalRead(pin string) (int, error) { + grovePin, grovePort, _, stateCmd, err := getGroveAddresses(pin) if err != nil { - return value, err + return 0, err } - err = g.SetGroveType(grovePort, CUSTOM) + err = d.SetGroveType(grovePort, CUSTOM) if err != nil { - return value, err + return 0, err } time.Sleep(10 * time.Millisecond) - err = g.SetGroveMode(grovePin, GROVE_INPUT_DIGITAL) + err = d.SetGroveMode(grovePin, GROVE_INPUT_DIGITAL) if err != nil { - return value, err + return 0, err } time.Sleep(10 * time.Millisecond) - response, err := g.readBytes(goPiGo3Address, stateCmd, 6) + response, err := d.readBytes(goPiGo3Address, stateCmd, 6) if err != nil { - return value, err + return 0, err } - if err := g.responseValid(response); err != nil { - return value, err + if err := d.responseValid(response); err != nil { + return 0, err } - if err := g.valueValid(response); err != nil { - return value, err + if err := d.valueValid(response); err != nil { + return 0, err } return int(response[5]), nil } +//nolint:nonamedreturns // sufficient here func getGroveAddresses(pin string) (gPin, gPort Grove, analog, state byte, err error) { switch pin { case "AD_1_1": @@ -661,75 +674,74 @@ func getGroveAddresses(pin string) (gPin, gPort Grove, analog, state byte, err e return gPin, gPort, analog, state, err } -func (g *Driver) responseValid(response []byte) error { +func (d *Driver) responseValid(response []byte) error { if response[3] != 0xA5 { return fmt.Errorf("No SPI response, response not valid") } return nil } -func (g *Driver) valueValid(value []byte) error { +func (d *Driver) valueValid(value []byte) error { if value[4] != byte(VALID_DATA) { return fmt.Errorf("Invalid value") } return nil } -func (g *Driver) readBytes(address byte, msg byte, numBytes int) (val []byte, err error) { +func (d *Driver) readBytes(address byte, msg byte, numBytes int) ([]byte, error) { w := make([]byte, numBytes) w[0] = address w[1] = msg r := make([]byte, len(w)) - err = g.connection.ReadCommandData(w, r) - if err != nil { - return val, err + if err := d.connection.ReadCommandData(w, r); err != nil { + return nil, err } return r, nil } -func (g *Driver) readUint16(address, msg byte) (val uint16, err error) { - r, err := g.readBytes(address, msg, 8) +func (d *Driver) readUint16(address, msg byte) (uint16, error) { + r, err := d.readBytes(address, msg, 8) if err != nil { - return val, err + return 0, err } - if err := g.responseValid(r); err != nil { - return val, err + if err := d.responseValid(r); err != nil { + return 0, err } return uint16(r[4])<<8 | uint16(r[5]), nil } -func (g *Driver) readUint32(address, msg byte) (val uint32, err error) { - r, err := g.readBytes(address, msg, 8) +func (d *Driver) readUint32(address, msg byte) (uint32, error) { + r, err := d.readBytes(address, msg, 8) if err != nil { - return val, err + return 0, err } - if err := g.responseValid(r); err != nil { - return val, err + if err := d.responseValid(r); err != nil { + return 0, err } return uint32(r[4])<<24 | uint32(r[5])<<16 | uint32(r[6])<<8 | uint32(r[7]), nil } -func (g *Driver) writeBytes(w []byte) error { - return g.connection.WriteBytes(w) +func (d *Driver) writeBytes(w []byte) error { + return d.connection.WriteBytes(w) } -func (g *Driver) resetAll() error { - err := g.SetGroveType(AD_1_G+AD_2_G, CUSTOM) +func (d *Driver) resetAll() error { + err := d.SetGroveType(AD_1_G+AD_2_G, CUSTOM) time.Sleep(10 * time.Millisecond) - if e := g.SetGroveMode(AD_1_G+AD_2_G, GROVE_INPUT_DIGITAL); e != nil { + if e := d.SetGroveMode(AD_1_G+AD_2_G, GROVE_INPUT_DIGITAL); e != nil { err = multierror.Append(err, e) } time.Sleep(10 * time.Millisecond) - if e := g.SetMotorPower(MOTOR_LEFT+MOTOR_RIGHT, 0.0); e != nil { + if e := d.SetMotorPower(MOTOR_LEFT+MOTOR_RIGHT, 0.0); e != nil { err = multierror.Append(err, e) } - if e := g.SetMotorLimits(MOTOR_LEFT+MOTOR_RIGHT, 0, 0); e != nil { + if e := d.SetMotorLimits(MOTOR_LEFT+MOTOR_RIGHT, 0, 0); e != nil { err = multierror.Append(err, e) } - if e := g.SetServo(SERVO_1+SERVO_2, 0); e != nil { + if e := d.SetServo(SERVO_1+SERVO_2, 0); e != nil { err = multierror.Append(err, e) } - if e := g.SetLED(LED_EYE_LEFT+LED_EYE_RIGHT+LED_BLINKER_LEFT+LED_BLINKER_RIGHT, 0, 0, 0); e != nil { + if e := d.SetLED(LED_EYE_LEFT+LED_EYE_RIGHT+LED_BLINKER_LEFT+LED_BLINKER_RIGHT, 0, 0, 0); e != nil { err = multierror.Append(err, e) } diff --git a/platforms/dexter/gopigo3/driver_test.go b/platforms/dexter/gopigo3/driver_test.go index 10e20658d..5e76c1ccd 100644 --- a/platforms/dexter/gopigo3/driver_test.go +++ b/platforms/dexter/gopigo3/driver_test.go @@ -4,7 +4,9 @@ import ( "encoding/hex" "testing" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/spi" ) @@ -31,226 +33,163 @@ func TestDriverHalt(t *testing.T) { } func TestDriverManufacturerName(t *testing.T) { - expectedName := "Dexter Industries" + wantName := "Dexter Industries" d := initTestDriver() name, err := d.GetManufacturerName() - if err != nil { - t.Error(err) - } - if name != expectedName { - t.Errorf("Expected name: %x, got: %x", expectedName, name) - } + require.NoError(t, err) + assert.Equal(t, wantName, name) } func TestDriverBoardName(t *testing.T) { - expectedBoardName := "GoPiGo3" + wantBoardName := "GoPiGo3" d := initTestDriver() name, err := d.GetBoardName() - if err != nil { - t.Error(err) - } - if name != expectedBoardName { - t.Errorf("Expected name: %s, got: %s", expectedBoardName, name) - } + require.NoError(t, err) + assert.Equal(t, wantBoardName, name) } func TestDriverHardwareVersion(t *testing.T) { - expectedHwVer := "3.1.3" + wantHwVer := "3.1.3" d := initTestDriver() ver, err := d.GetHardwareVersion() - if err != nil { - t.Error(err) - } - if ver != expectedHwVer { - t.Errorf("Expected hw ver: %s, got: %s", expectedHwVer, ver) - } + require.NoError(t, err) + assert.Equal(t, wantHwVer, ver) } func TestDriverFirmareVersion(t *testing.T) { - expectedFwVer := "0.3.4" + wantFwVer := "0.3.4" d := initTestDriver() ver, err := d.GetFirmwareVersion() - if err != nil { - t.Error(err) - } - if ver != expectedFwVer { - t.Errorf("Expected fw ver: %s, got: %s", expectedFwVer, ver) - } + require.NoError(t, err) + assert.Equal(t, wantFwVer, ver) } func TestGetSerialNumber(t *testing.T) { - expectedSerialNumber := "E0180A54514E343732202020FF112137" + wantSerialNumber := "E0180A54514E343732202020FF112137" d := initTestDriver() serial, err := d.GetSerialNumber() - if err != nil { - t.Error(err) - } - if serial != expectedSerialNumber { - t.Errorf("Expected serial number: %s, got: %s", expectedSerialNumber, serial) - } + require.NoError(t, err) + assert.Equal(t, wantSerialNumber, serial) } func TestGetFiveVolts(t *testing.T) { - expectedVoltage := float32(5.047000) + wantVoltage := float32(5.047000) d := initTestDriver() voltage, err := d.Get5vVoltage() - if err != nil { - t.Error(err) - } - if voltage != expectedVoltage { - t.Errorf("Expected 5v voltage: %f, got: %f", expectedVoltage, voltage) - } + require.NoError(t, err) + assert.InDelta(t, wantVoltage, voltage, 0.0) } func TestGetBatVolts(t *testing.T) { - expectedBatVoltage := float32(15.411000) + wantBatVoltage := float32(15.411000) d := initTestDriver() voltage, err := d.GetBatteryVoltage() - if err != nil { - t.Error(err) - } - if voltage != expectedBatVoltage { - t.Errorf("Expected battery voltage: %f, got: %f", expectedBatVoltage, voltage) - } + require.NoError(t, err) + assert.InDelta(t, wantBatVoltage, voltage, 0.0) } func TestGetMotorStatus(t *testing.T) { - expectedPower := uint16(65408) + wantPower := uint16(65408) d := initTestDriver() - _, power, _, _, err := d.GetMotorStatus(MOTOR_LEFT) - if err != nil { - t.Error(err) - } - if power != expectedPower { - t.Errorf("Expected power: %d, got: %d", expectedPower, power) - } + f1, power, f2, f3, err := d.GetMotorStatus(MOTOR_LEFT) + require.NoError(t, err) + assert.Equal(t, wantPower, power) + assert.Equal(t, uint8(0), f1) + assert.Equal(t, 0, f2) + assert.Equal(t, 0, f3) } func TestGetEncoderStatusPos(t *testing.T) { negativeEncoder = false - expectedEncoderValue := int64(127) + wantEncoderValue := int64(127) d := initTestDriver() encoderValue, err := d.GetMotorEncoder(MOTOR_LEFT) - if err != nil { - t.Error(err) - } - if encoderValue != expectedEncoderValue { - t.Errorf("Expected encoder value: %d, got: %d", expectedEncoderValue, encoderValue) - } + require.NoError(t, err) + assert.Equal(t, wantEncoderValue, encoderValue) } func TestGetEncoderStatusNeg(t *testing.T) { negativeEncoder = true - expectedEncoderValue := int64(-128) + wantEncoderValue := int64(-128) d := initTestDriver() encoderValue, err := d.GetMotorEncoder(MOTOR_LEFT) - if err != nil { - t.Error(err) - } - if encoderValue != expectedEncoderValue { - t.Errorf("Expected encoder value: %d, got: %d", expectedEncoderValue, encoderValue) - } + require.NoError(t, err) + assert.Equal(t, wantEncoderValue, encoderValue) } func TestAnalogRead(t *testing.T) { - expectedVal := 160 + wantVal := 160 d := initTestDriver() val, err := d.AnalogRead("AD_1_1") - if err != nil { - t.Error(err) - } - if val != expectedVal { - t.Errorf("Expected value: %d, got: %d", expectedVal, val) - } + require.NoError(t, err) + assert.Equal(t, wantVal, val) } func TestDigitalRead(t *testing.T) { - expectedVal := 1 + wantVal := 1 d := initTestDriver() val, err := d.DigitalRead("AD_1_2") - if err != nil { - t.Error(err) - } - if val != expectedVal { - t.Errorf("Expected value: %d, got: %d", expectedVal, val) - } + require.NoError(t, err) + assert.Equal(t, wantVal, val) } func TestServoWrite(t *testing.T) { d := initTestDriver() err := d.ServoWrite("SERVO_1", 0x7F) - if err != nil { - t.Error(err) - } + require.NoError(t, err) } func TestSetMotorPosition(t *testing.T) { d := initTestDriver() err := d.SetMotorPosition(MOTOR_LEFT, 12.0) - if err != nil { - t.Error(err) - } + require.NoError(t, err) } func TestSetMotorPower(t *testing.T) { d := initTestDriver() err := d.SetMotorPower(MOTOR_LEFT, 127) - if err != nil { - t.Error(err) - } + require.NoError(t, err) } func TestSetMotorDps(t *testing.T) { d := initTestDriver() err := d.SetMotorDps(MOTOR_LEFT, 12.0) - if err != nil { - t.Error(err) - } + require.NoError(t, err) } func TestOffsetMotorEncoder(t *testing.T) { d := initTestDriver() err := d.OffsetMotorEncoder(MOTOR_LEFT, 12.0) - if err != nil { - t.Error(err) - } + require.NoError(t, err) } func TestSetPWMDuty(t *testing.T) { d := initTestDriver() err := d.SetPWMDuty(AD_1_1_G, 80) - if err != nil { - t.Error(err) - } + require.NoError(t, err) } func TestSetPWMfreq(t *testing.T) { d := initTestDriver() err := d.SetPWMFreq(AD_1_2_G, 100) - if err != nil { - t.Error(err) - } + require.NoError(t, err) } func TestPwmWrite(t *testing.T) { d := initTestDriver() err := d.PwmWrite("AD_2_2", 80) - if err != nil { - t.Error(err) - } + require.NoError(t, err) } func TestDigitalWrite(t *testing.T) { d := initTestDriver() err := d.DigitalWrite("AD_2_1", 1) - if err != nil { - t.Error(err) - } + require.NoError(t, err) } type TestConnector struct{} -func (ctr *TestConnector) GetSpiConnection(busNum, chipNum, mode, bits int, maxSpeed int64) (device spi.Connection, err error) { +func (ctr *TestConnector) GetSpiConnection(busNum, chipNum, mode, bits int, maxSpeed int64) (spi.Connection, error) { return TestSpiDevice{}, nil } diff --git a/platforms/digispark/digispark_adaptor.go b/platforms/digispark/digispark_adaptor.go index 29c0815b0..7d715ab8c 100644 --- a/platforms/digispark/digispark_adaptor.go +++ b/platforms/digispark/digispark_adaptor.go @@ -19,19 +19,20 @@ type Adaptor struct { servo bool pwm bool i2c bool - connect func(*Adaptor) (err error) + connect func(*Adaptor) error } // NewAdaptor returns a new Digispark Adaptor func NewAdaptor() *Adaptor { return &Adaptor{ name: gobot.DefaultName("Digispark"), - connect: func(d *Adaptor) (err error) { + connect: func(d *Adaptor) error { d.littleWire = littleWireConnect() + //nolint:forcetypeassert // ok here if d.littleWire.(*littleWire).lwHandle == nil { return ErrConnection } - return + return nil }, } } @@ -43,37 +44,36 @@ func (d *Adaptor) Name() string { return d.name } func (d *Adaptor) SetName(n string) { d.name = n } // Connect starts a connection to the digispark -func (d *Adaptor) Connect() (err error) { - err = d.connect(d) - return +func (d *Adaptor) Connect() error { + return d.connect(d) } // Finalize implements the Adaptor interface -func (d *Adaptor) Finalize() (err error) { return } +func (d *Adaptor) Finalize() error { return nil } // DigitalWrite writes a value to the pin. Acceptable values are 1 or 0. -func (d *Adaptor) DigitalWrite(pin string, level byte) (err error) { +func (d *Adaptor) DigitalWrite(pin string, level byte) error { p, err := strconv.Atoi(pin) if err != nil { - return + return err } - if err = d.littleWire.pinMode(uint8(p), 0); err != nil { - return + if err := d.littleWire.pinMode(uint8(p), 0); err != nil { + return err } return d.littleWire.digitalWrite(uint8(p), level) } // PwmWrite writes the 0-254 value to the specified pin -func (d *Adaptor) PwmWrite(pin string, value byte) (err error) { +func (d *Adaptor) PwmWrite(pin string, value byte) error { if !d.pwm { - if err = d.littleWire.pwmInit(); err != nil { - return + if err := d.littleWire.pwmInit(); err != nil { + return err } - if err = d.littleWire.pwmUpdatePrescaler(1); err != nil { - return + if err := d.littleWire.pwmUpdatePrescaler(1); err != nil { + return err } d.pwm = true } @@ -82,10 +82,10 @@ func (d *Adaptor) PwmWrite(pin string, value byte) (err error) { } // ServoWrite writes the 0-180 degree val to the specified pin. -func (d *Adaptor) ServoWrite(pin string, angle uint8) (err error) { +func (d *Adaptor) ServoWrite(pin string, angle uint8) error { if !d.servo { - if err = d.littleWire.servoInit(); err != nil { - return + if err := d.littleWire.servoInit(); err != nil { + return err } d.servo = true } @@ -94,7 +94,7 @@ func (d *Adaptor) ServoWrite(pin string, angle uint8) (err error) { // GetI2cConnection returns an i2c connection to a device on a specified bus. // Only supports bus number 0 -func (d *Adaptor) GetI2cConnection(address int, bus int) (connection i2c.Connection, err error) { +func (d *Adaptor) GetI2cConnection(address int, bus int) (i2c.Connection, error) { if bus != 0 { return nil, fmt.Errorf("Invalid bus number %d, only 0 is supported", bus) } diff --git a/platforms/digispark/digispark_adaptor_test.go b/platforms/digispark/digispark_adaptor_test.go index 2c1610d58..677018fa6 100644 --- a/platforms/digispark/digispark_adaptor_test.go +++ b/platforms/digispark/digispark_adaptor_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert // ok here package digispark import ( @@ -7,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/gpio" ) @@ -77,7 +79,7 @@ func (l *mock) i2cUpdateDelay(duration uint) error func initTestAdaptor() *Adaptor { a := NewAdaptor() - a.connect = func(a *Adaptor) (err error) { return nil } + a.connect = func(a *Adaptor) error { return nil } a.littleWire = new(mock) errorFunc = func() error { return nil } pwmInitErrorFunc = func() error { return nil } diff --git a/platforms/digispark/digispark_i2c.go b/platforms/digispark/digispark_i2c.go index 6249c2a20..b63f50f1e 100644 --- a/platforms/digispark/digispark_i2c.go +++ b/platforms/digispark/digispark_i2c.go @@ -15,19 +15,19 @@ type digisparkI2cConnection struct { // NewDigisparkI2cConnection creates an i2c connection to an i2c device at // the specified address -func NewDigisparkI2cConnection(adaptor *Adaptor, address uint8) (connection *digisparkI2cConnection) { +func NewDigisparkI2cConnection(adaptor *Adaptor, address uint8) *digisparkI2cConnection { return &digisparkI2cConnection{adaptor: adaptor, address: address} } // Init makes sure that the i2c device is already initialized -func (c *digisparkI2cConnection) Init() (err error) { +func (c *digisparkI2cConnection) Init() error { if !c.adaptor.i2c { - if err = c.adaptor.littleWire.i2cInit(); err != nil { - return + if err := c.adaptor.littleWire.i2cInit(); err != nil { + return err } c.adaptor.i2c = true } - return + return nil } // Test tests i2c connection with the given address @@ -48,7 +48,7 @@ func (c *digisparkI2cConnection) UpdateDelay(duration uint) error { // Read tries to read a full buffer from the i2c device. // Returns an empty array if the response from the board has timed out. -func (c *digisparkI2cConnection) Read(b []byte) (countRead int, err error) { +func (c *digisparkI2cConnection) Read(b []byte) (int, error) { c.mtx.Lock() defer c.mtx.Unlock() @@ -56,7 +56,7 @@ func (c *digisparkI2cConnection) Read(b []byte) (countRead int, err error) { } // Write writes the buffer content in data to the i2c device. -func (c *digisparkI2cConnection) Write(data []byte) (countWritten int, err error) { +func (c *digisparkI2cConnection) Write(data []byte) (int, error) { c.mtx.Lock() defer c.mtx.Unlock() @@ -69,61 +69,61 @@ func (c *digisparkI2cConnection) Close() error { } // ReadByte reads one byte from the i2c device. -func (c *digisparkI2cConnection) ReadByte() (val byte, err error) { +func (c *digisparkI2cConnection) ReadByte() (byte, error) { c.mtx.Lock() defer c.mtx.Unlock() buf := []byte{0} - if err = c.readAndCheckCount(buf); err != nil { - return + if err := c.readAndCheckCount(buf); err != nil { + return 0, err } - val = buf[0] - return + val := buf[0] + return val, nil } // ReadByteData reads one byte of the given register address from the i2c device. -func (c *digisparkI2cConnection) ReadByteData(reg uint8) (val uint8, err error) { +func (c *digisparkI2cConnection) ReadByteData(reg uint8) (uint8, error) { c.mtx.Lock() defer c.mtx.Unlock() - if err = c.writeAndCheckCount([]byte{reg}, false); err != nil { - return + if err := c.writeAndCheckCount([]byte{reg}, false); err != nil { + return 0, err } buf := []byte{0} - if err = c.readAndCheckCount(buf); err != nil { - return + if err := c.readAndCheckCount(buf); err != nil { + return 0, err } - val = buf[0] - return + val := buf[0] + return val, nil } // ReadWordData reads two bytes of the given register address from the i2c device. -func (c *digisparkI2cConnection) ReadWordData(reg uint8) (val uint16, err error) { +func (c *digisparkI2cConnection) ReadWordData(reg uint8) (uint16, error) { c.mtx.Lock() defer c.mtx.Unlock() - if err = c.writeAndCheckCount([]byte{reg}, false); err != nil { - return + if err := c.writeAndCheckCount([]byte{reg}, false); err != nil { + return 0, err } buf := []byte{0, 0} - if err = c.readAndCheckCount(buf); err != nil { - return + if err := c.readAndCheckCount(buf); err != nil { + return 0, err } low, high := buf[0], buf[1] - val = (uint16(high) << 8) | uint16(low) - return + val := (uint16(high) << 8) | uint16(low) + return val, nil } // ReadBlockData reads a block of maximum 32 bytes from the given register address of the i2c device. -func (c *digisparkI2cConnection) ReadBlockData(reg uint8, data []byte) (err error) { +func (c *digisparkI2cConnection) ReadBlockData(reg uint8, data []byte) error { c.mtx.Lock() defer c.mtx.Unlock() - if err = c.writeAndCheckCount([]byte{reg}, false); err != nil { - return + if err := c.writeAndCheckCount([]byte{reg}, false); err != nil { + return err } if len(data) > 32 { @@ -212,42 +212,43 @@ func (c *digisparkI2cConnection) writeAndCheckCount(buf []byte, finalStop bool) return nil } -func (c *digisparkI2cConnection) readInternal(b []byte) (countRead int, err error) { +func (c *digisparkI2cConnection) readInternal(b []byte) (int, error) { if !c.adaptor.i2c { - err = errors.New("Digispark i2c not initialized") - return + err := errors.New("Digispark i2c not initialized") + return 0, err } - if err = c.adaptor.littleWire.i2cStart(c.address, 1); err != nil { - return + if err := c.adaptor.littleWire.i2cStart(c.address, 1); err != nil { + return 0, err } l := 8 stop := uint8(0) + var countRead int for stop == 0 { if countRead+l >= len(b) { l = len(b) - countRead stop = 1 } - if err = c.adaptor.littleWire.i2cRead(b[countRead:countRead+l], l, stop); err != nil { - return + if err := c.adaptor.littleWire.i2cRead(b[countRead:countRead+l], l, stop); err != nil { + return countRead, err } countRead += l } - return + return countRead, nil } -func (c *digisparkI2cConnection) writeInternal(data []byte, finalStop bool) (countWritten int, err error) { +func (c *digisparkI2cConnection) writeInternal(data []byte, finalStop bool) (int, error) { if !c.adaptor.i2c { - err = errors.New("Digispark i2c not initialized") - return + return 0, errors.New("Digispark i2c not initialized") } - if err = c.adaptor.littleWire.i2cStart(c.address, 0); err != nil { - return + if err := c.adaptor.littleWire.i2cStart(c.address, 0); err != nil { + return 0, err } l := 4 lastQuadruplet := false stop := uint8(0) + var countWritten int for !lastQuadruplet { if countWritten+l >= len(data) { lastQuadruplet = true @@ -256,10 +257,10 @@ func (c *digisparkI2cConnection) writeInternal(data []byte, finalStop bool) (cou stop = 1 } } - if err = c.adaptor.littleWire.i2cWrite(data[countWritten:countWritten+l], l, stop); err != nil { - return + if err := c.adaptor.littleWire.i2cWrite(data[countWritten:countWritten+l], l, stop); err != nil { + return countWritten, err } countWritten += l } - return + return countWritten, nil } diff --git a/platforms/digispark/digispark_i2c_test.go b/platforms/digispark/digispark_i2c_test.go index ff6412255..b14b7fb38 100644 --- a/platforms/digispark/digispark_i2c_test.go +++ b/platforms/digispark/digispark_i2c_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert // ok here package digispark import ( @@ -6,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2/drivers/i2c" ) @@ -31,7 +33,7 @@ type i2cMock struct { func initTestAdaptorI2c() *Adaptor { a := NewAdaptor() - a.connect = func(a *Adaptor) (err error) { return nil } + a.connect = func(a *Adaptor) error { return nil } a.littleWire = new(i2cMock) return a } diff --git a/platforms/digispark/littleWire.go b/platforms/digispark/littleWire.go index f88c8990b..39f129c1e 100644 --- a/platforms/digispark/littleWire.go +++ b/platforms/digispark/littleWire.go @@ -3,7 +3,7 @@ package digispark //#cgo pkg-config: libusb //#include "littleWire.h" //#include "littleWire_servo.h" -//typedef usb_dev_handle littleWire; +// typedef usb_dev_handle littleWire; import "C" import ( diff --git a/platforms/dji/tello/crc.go b/platforms/dji/tello/crc.go index 3aa031b0d..27ef8da15 100644 --- a/platforms/dji/tello/crc.go +++ b/platforms/dji/tello/crc.go @@ -29,6 +29,7 @@ func CalculateCRC8(pkt []byte) byte { return crc } +//nolint:lll // ok here var crc16table = []uint16{ 0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf, 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7, 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e, 0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876, diff --git a/platforms/dji/tello/driver.go b/platforms/dji/tello/driver.go index 808993c05..0510c0316 100644 --- a/platforms/dji/tello/driver.go +++ b/platforms/dji/tello/driver.go @@ -205,8 +205,8 @@ func NewDriver(port string) *Driver { return NewDriverWithIP("192.168.10.1", port) } -// 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. +// 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"), @@ -533,6 +533,8 @@ func bound(x, y float32) float32 { //nolint:unparam // keep y as parameter // Values are from 0 to 1. // x, y, z denote forward, side and vertical translation, // and psi yaw (rotation around the z-axis). +// +//nolint:nonamedreturns // sufficient here func (d *Driver) Vector() (x, y, z, psi float32) { return d.ry, d.rx, d.ly, d.lx } @@ -890,7 +892,8 @@ func (d *Driver) SendStickCommand() error { // speed control axis5 := int16(d.throttle) - packedAxis := int64(axis1)&0x7FF | int64(axis2&0x7FF)<<11 | 0x7FF&int64(axis3)<<22 | 0x7FF&int64(axis4)<<33 | int64(axis5)<<44 + packedAxis := int64(axis1)&0x7FF | int64(axis2&0x7FF)<<11 | 0x7FF&int64(axis3)<<22 | 0x7FF&int64(axis4)<<33 | + int64(axis5)<<44 if err := binary.Write(buf, binary.LittleEndian, byte(0xFF&packedAxis)); err != nil { return err } @@ -1071,8 +1074,8 @@ func (d *Driver) processVideo() error { return nil } -func (d *Driver) createPacket(cmd int16, pktType byte, len int16) (*bytes.Buffer, error) { - l := len + 11 +func (d *Driver) createPacket(cmd int16, pktType byte, pktLen int16) (*bytes.Buffer, error) { + l := pktLen + 11 buf := &bytes.Buffer{} if err := binary.Write(buf, binary.LittleEndian, byte(messageStart)); err != nil { diff --git a/platforms/dji/tello/driver_test.go b/platforms/dji/tello/driver_test.go index 3571c0160..cef8c2c08 100644 --- a/platforms/dji/tello/driver_test.go +++ b/platforms/dji/tello/driver_test.go @@ -10,6 +10,8 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -17,7 +19,7 @@ var _ gobot.Driver = (*Driver)(nil) type WriteCloserDoNothing struct{} -func (w *WriteCloserDoNothing) Write(p []byte) (n int, err error) { +func (w *WriteCloserDoNothing) Write(p []byte) (int, error) { return 0, nil } @@ -113,9 +115,7 @@ func Test_handleResponse(t *testing.T) { d := NewDriver("8888") events := d.Subscribe() err := d.handleResponse(bytes.NewReader(tc.msg)) - if tc.err != err { - t.Errorf("expected '%v' error, got: %v", tc.err, err) - } + require.ErrorIs(t, tc.err, err) if tc.wantEvent != "" { select { case ev, ok := <-events: diff --git a/platforms/dragonboard/dragonboard_adaptor.go b/platforms/dragonboard/dragonboard_adaptor.go index cd79f5117..0f75eac41 100644 --- a/platforms/dragonboard/dragonboard_adaptor.go +++ b/platforms/dragonboard/dragonboard_adaptor.go @@ -5,6 +5,7 @@ import ( "sync" multierror "github.com/hashicorp/go-multierror" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/platforms/adaptors" "gobot.io/x/gobot/v2/system" diff --git a/platforms/dragonboard/dragonboard_adaptor_test.go b/platforms/dragonboard/dragonboard_adaptor_test.go index d6c8fe4b0..cd8cb6adf 100644 --- a/platforms/dragonboard/dragonboard_adaptor_test.go +++ b/platforms/dragonboard/dragonboard_adaptor_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/gpio" "gobot.io/x/gobot/v2/drivers/i2c" @@ -77,7 +78,7 @@ func TestFinalizeErrorAfterGPIO(t *testing.T) { fs.WithWriteError = true err := a.Finalize() - assert.Contains(t, err.Error(), "write error") + require.ErrorContains(t, err, "write error") } func TestI2cDefaultBus(t *testing.T) { @@ -99,7 +100,7 @@ func TestI2cFinalizeWithErrors(t *testing.T) { // act err = a.Finalize() // assert - assert.Contains(t, err.Error(), "close error") + require.ErrorContains(t, err, "close error") } func Test_validateI2cBusNumber(t *testing.T) { diff --git a/platforms/firmata/ble_firmata_adaptor.go b/platforms/firmata/ble_firmata_adaptor.go index 2aa8d2a6c..7150b8de5 100644 --- a/platforms/firmata/ble_firmata_adaptor.go +++ b/platforms/firmata/ble_firmata_adaptor.go @@ -27,10 +27,11 @@ type BLEAdaptor struct { // NewBLEAdaptor opens and uses a BLE connection to a // microcontroller running FirmataBLE func NewBLEAdaptor(args ...interface{}) *BLEAdaptor { - address := args[0].(string) + address := args[0].(string) //nolint:forcetypeassert // ok here rid := ReceiveID wid := TransmitID + //nolint:forcetypeassert // ok here if len(args) >= 3 { rid = args[1].(string) wid = args[2].(string) diff --git a/platforms/firmata/ble_firmata_adaptor_test.go b/platforms/firmata/ble_firmata_adaptor_test.go index 0e6c88079..774f43c11 100644 --- a/platforms/firmata/ble_firmata_adaptor_test.go +++ b/platforms/firmata/ble_firmata_adaptor_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/firmata/client/client.go b/platforms/firmata/client/client.go index d445ed2a2..0f0f6f246 100644 --- a/platforms/firmata/client/client.go +++ b/platforms/firmata/client/client.go @@ -135,11 +135,13 @@ func (b *Client) Disconnect() error { // Connecting returns true when the client is connecting func (b *Client) Connecting() bool { + //nolint:forcetypeassert // ok here return b.connecting.Load().(bool) } // Connected returns the current connection state of the Client func (b *Client) Connected() bool { + //nolint:forcetypeassert // ok here return b.connected.Load().(bool) } @@ -371,7 +373,7 @@ func (b *Client) WriteSysex(data []byte) error { } func (b *Client) write(data []byte) error { - _, err := b.connection.Write(data[:]) + _, err := b.connection.Write(data) return err } @@ -530,7 +532,7 @@ func (b *Client) process() error { name = append(name, val) } } - b.FirmwareName = string(name[:]) + b.FirmwareName = string(name) b.Publish(b.Event("FirmwareQuery"), b.FirmwareName) case StringData: str := currentBuffer[2:] diff --git a/platforms/firmata/firmata_adaptor.go b/platforms/firmata/firmata_adaptor.go index 4246b14d2..24f64f9c5 100644 --- a/platforms/firmata/firmata_adaptor.go +++ b/platforms/firmata/firmata_adaptor.go @@ -10,6 +10,7 @@ import ( "time" "go.bug.st/serial" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/i2c" "gobot.io/x/gobot/v2/platforms/firmata/client" @@ -19,7 +20,7 @@ type firmataBoard interface { Connect(conn io.ReadWriteCloser) error Disconnect() error Pins() []client.Pin - AnalogWrite(pin int, value int) (err error) + AnalogWrite(pin int, value int) error SetPinMode(pin int, mode int) error ReportAnalog(pin int, state int) error ReportDigital(pin int, state int) error @@ -186,18 +187,18 @@ func (f *Adaptor) DigitalWrite(pin string, level byte) error { // DigitalRead retrieves digital value from specified pin. // Returns -1 if the response from the board has timed out -func (f *Adaptor) DigitalRead(pin string) (val int, err error) { +func (f *Adaptor) DigitalRead(pin string) (int, error) { p, err := strconv.Atoi(pin) if err != nil { - return + return 0, err } if f.Board.Pins()[p].Mode != client.Input { - if err = f.Board.SetPinMode(p, client.Input); err != nil { - return + if err := f.Board.SetPinMode(p, client.Input); err != nil { + return 0, err } - if err = f.Board.ReportDigital(p, 1); err != nil { - return + if err := f.Board.ReportDigital(p, 1); err != nil { + return 0, err } <-time.After(10 * time.Millisecond) } diff --git a/platforms/firmata/firmata_adaptor_test.go b/platforms/firmata/firmata_adaptor_test.go index 23ecf4591..1e62a7abf 100644 --- a/platforms/firmata/firmata_adaptor_test.go +++ b/platforms/firmata/firmata_adaptor_test.go @@ -1,6 +1,7 @@ //go:build !windows // +build !windows +//nolint:forcetypeassert // ok here package firmata import ( @@ -11,6 +12,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/aio" "gobot.io/x/gobot/v2/drivers/gpio" diff --git a/platforms/firmata/firmata_i2c.go b/platforms/firmata/firmata_i2c.go index 4e7759a10..e4c5d8714 100644 --- a/platforms/firmata/firmata_i2c.go +++ b/platforms/firmata/firmata_i2c.go @@ -19,13 +19,13 @@ type firmataI2cConnection struct { // NewFirmataI2cConnection creates an I2C connection to an I2C device at // the specified address -func NewFirmataI2cConnection(adaptor *Adaptor, address int) (connection *firmataI2cConnection) { +func NewFirmataI2cConnection(adaptor *Adaptor, address int) *firmataI2cConnection { return &firmataI2cConnection{adaptor: adaptor, address: address} } // Read tries to read a full buffer from the i2c device. // Returns an empty array if the response from the board has timed out. -func (c *firmataI2cConnection) Read(b []byte) (read int, err error) { +func (c *firmataI2cConnection) Read(b []byte) (int, error) { c.mtx.Lock() defer c.mtx.Unlock() @@ -33,7 +33,7 @@ func (c *firmataI2cConnection) Read(b []byte) (read int, err error) { } // Write writes the buffer content in data to the i2c device. -func (c *firmataI2cConnection) Write(data []byte) (written int, err error) { +func (c *firmataI2cConnection) Write(data []byte) (int, error) { c.mtx.Lock() defer c.mtx.Unlock() @@ -205,7 +205,7 @@ func (c *firmataI2cConnection) readInternal(b []byte) (int, error) { } if err := c.adaptor.Board.Once(c.adaptor.Board.Event("I2cReply"), func(data interface{}) { - ret <- data.(client.I2cReply).Data + ret <- data.(client.I2cReply).Data //nolint:forcetypeassert // ok here }); err != nil { return 0, err } @@ -227,7 +227,7 @@ func (c *firmataI2cConnection) writeInternal(data []byte) (int, error) { written += len(chunk) } if len(data) > 0 { - if err := c.adaptor.Board.I2cWrite(c.address, data[:]); err != nil { + if err := c.adaptor.Board.I2cWrite(c.address, data); err != nil { return written, err } written += len(data) diff --git a/platforms/firmata/firmata_i2c_test.go b/platforms/firmata/firmata_i2c_test.go index 4a12040ec..8b06ca6f6 100644 --- a/platforms/firmata/firmata_i2c_test.go +++ b/platforms/firmata/firmata_i2c_test.go @@ -1,6 +1,7 @@ //go:build !windows // +build !windows +//nolint:forcetypeassert // ok here package firmata import ( @@ -10,6 +11,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/i2c" "gobot.io/x/gobot/v2/platforms/firmata/client" diff --git a/platforms/firmata/tcp_firmata_adaptor.go b/platforms/firmata/tcp_firmata_adaptor.go index af34cac96..5a5b47b6e 100644 --- a/platforms/firmata/tcp_firmata_adaptor.go +++ b/platforms/firmata/tcp_firmata_adaptor.go @@ -16,22 +16,20 @@ type TCPAdaptor struct { *Adaptor } -func connect(address string) (io.ReadWriteCloser, error) { - return net.Dial("tcp", address) -} - // NewTCPAdaptor opens and uses a TCP connection to a microcontroller running // WiFiFirmata func NewTCPAdaptor(args ...interface{}) *TCPAdaptor { - address := args[0].(string) + address := args[0].(string) //nolint:forcetypeassert // ok here a := NewAdaptor(address) a.SetName(gobot.DefaultName("TCPFirmata")) - a.PortOpener = func(port string) (io.ReadWriteCloser, error) { - return connect(port) - } + a.PortOpener = connect return &TCPAdaptor{ Adaptor: a, } } + +func connect(address string) (io.ReadWriteCloser, error) { + return net.Dial("tcp", address) +} diff --git a/platforms/firmata/tcp_firmata_adaptor_test.go b/platforms/firmata/tcp_firmata_adaptor_test.go index b63937a21..b5d8542af 100644 --- a/platforms/firmata/tcp_firmata_adaptor_test.go +++ b/platforms/firmata/tcp_firmata_adaptor_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/holystone/holystone.go b/platforms/holystone/holystone.go index 6a9ea73b7..a1f233583 100644 --- a/platforms/holystone/holystone.go +++ b/platforms/holystone/holystone.go @@ -2,4 +2,6 @@ // Currently only have support for the HS200 drone. // For more information, go to: // http://www.holystone.com/product/Holy_Stone_HS200W_FPV_Drone_with_720P_HD_Live_Video_Wifi_Camera_2_4GHz_4CH_6_Axis_Gyro_RC_Quadcopter_with_Altitude_Hold,_Gravity_Sensor_and_Headless_Mode_Function_RTF,_Color_Red-39.html +// +//nolint:lll // ok here package holystone // import "gobot.io/x/gobot/v2/platforms/holystone" diff --git a/platforms/holystone/hs200/hs200_driver.go b/platforms/holystone/hs200/hs200_driver.go index e11f4114d..477c1561f 100644 --- a/platforms/holystone/hs200/hs200_driver.go +++ b/platforms/holystone/hs200/hs200_driver.go @@ -61,7 +61,7 @@ func (d *Driver) SetName(n string) { d.name = n } func (d *Driver) Connection() gobot.Connection { return nil } // Start starts the driver. -func (d *Driver) Start() (err error) { +func (d *Driver) Start() error { tc, terr := net.Dial("tcp", d.tcpaddress) if terr != nil { return terr @@ -74,13 +74,13 @@ func (d *Driver) Start() (err error) { d.udpconn = uc d.tcpconn = tc - return + return nil } // Halt stops the driver. -func (d *Driver) Halt() (err error) { +func (d *Driver) Halt() error { d.stop() - return + return nil } func (d *Driver) stop() { diff --git a/platforms/holystone/hs200/hs200_driver_test.go b/platforms/holystone/hs200/hs200_driver_test.go index 42519a829..9bd32abe2 100644 --- a/platforms/holystone/hs200/hs200_driver_test.go +++ b/platforms/holystone/hs200/hs200_driver_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/intel-iot/curie/imu_driver.go b/platforms/intel-iot/curie/imu_driver.go index ea1e7852f..15998c84d 100644 --- a/platforms/intel-iot/curie/imu_driver.go +++ b/platforms/intel-iot/curie/imu_driver.go @@ -75,6 +75,7 @@ func NewIMUDriver(a *firmata.Adaptor) *IMUDriver { // Start starts up the IMUDriver func (imu *IMUDriver) Start() error { return imu.connection.On("SysexResponse", func(res interface{}) { + //nolint:forcetypeassert // ok here data := res.([]byte) if err := imu.handleEvent(data); err != nil { panic(err) diff --git a/platforms/intel-iot/curie/imu_driver_test.go b/platforms/intel-iot/curie/imu_driver_test.go index 051112fab..16422af86 100644 --- a/platforms/intel-iot/curie/imu_driver_test.go +++ b/platforms/intel-iot/curie/imu_driver_test.go @@ -8,8 +8,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "gobot.io/x/gobot/v2" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/platforms/firmata" "gobot.io/x/gobot/v2/platforms/firmata/client" ) @@ -216,7 +216,9 @@ func TestIMUDriverReadMotionData(t *testing.T) { _, err := parseMotionData([]byte{}) require.ErrorContains(t, err, "Invalid data") - result, err := parseMotionData([]byte{0xF0, 0x11, 0x06, 0x00, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0xf7}) + result, err := parseMotionData([]byte{ + 0xF0, 0x11, 0x06, 0x00, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0xf7, + }) require.NoError(t, err) assert.Equal(t, &MotionData{AX: 1920, AY: 1920, AZ: 1920, GX: 1920, GY: 1920, GZ: 1920}, result) } @@ -231,5 +233,7 @@ func TestIMUDriverHandleEvents(t *testing.T) { require.NoError(t, d.handleEvent([]byte{0xF0, 0x11, 0x03, 0x00, 0x02, 0xf7})) require.NoError(t, d.handleEvent([]byte{0xF0, 0x11, 0x04, 0x00, 0x02, 0xf7})) require.NoError(t, d.handleEvent([]byte{0xF0, 0x11, 0x05, 0x00, 0x02, 0xf7})) - require.NoError(t, d.handleEvent([]byte{0xF0, 0x11, 0x06, 0x00, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0xf7})) + require.NoError(t, d.handleEvent([]byte{ + 0xF0, 0x11, 0x06, 0x00, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0xf7, + })) } diff --git a/platforms/intel-iot/edison/edison_adaptor.go b/platforms/intel-iot/edison/edison_adaptor.go index bcd754126..17a7b24ff 100644 --- a/platforms/intel-iot/edison/edison_adaptor.go +++ b/platforms/intel-iot/edison/edison_adaptor.go @@ -7,6 +7,7 @@ import ( "sync" multierror "github.com/hashicorp/go-multierror" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/platforms/adaptors" "gobot.io/x/gobot/v2/system" @@ -104,7 +105,8 @@ func (c *Adaptor) Connect() error { } // Finalize releases all i2c devices and exported analog, digital, pwm pins. -func (c *Adaptor) Finalize() (err error) { +func (c *Adaptor) Finalize() error { + var err error if c.tristate != nil { if errs := c.tristate.Unexport(); errs != nil { err = multierror.Append(err, errs) @@ -129,23 +131,23 @@ func (c *Adaptor) Finalize() (err error) { err = multierror.Append(err, e) } c.arduinoI2cInitialized = false - return + return err } // DigitalRead reads digital value from pin -func (c *Adaptor) DigitalRead(pin string) (i int, err error) { +func (c *Adaptor) DigitalRead(pin string) (int, error) { c.mutex.Lock() defer c.mutex.Unlock() sysPin, err := c.digitalPin(pin, system.WithPinDirectionInput()) if err != nil { - return + return 0, err } return sysPin.Read() } // DigitalWrite writes a value to the pin. Acceptable values are 1 or 0. -func (c *Adaptor) DigitalWrite(pin string, val byte) (err error) { +func (c *Adaptor) DigitalWrite(pin string, val byte) error { c.mutex.Lock() defer c.mutex.Unlock() @@ -162,13 +164,13 @@ func (c *Adaptor) DigitalPin(id string) (gobot.DigitalPinner, error) { } // AnalogRead returns value from analog reading of specified pin -func (c *Adaptor) AnalogRead(pin string) (val int, err error) { +func (c *Adaptor) AnalogRead(pin string) (int, error) { buf, err := c.readFile("/sys/bus/iio/devices/iio:device1/in_voltage" + pin + "_raw") if err != nil { - return + return 0, err } - val, err = strconv.Atoi(string(buf[0 : len(buf)-1])) + val, err := strconv.Atoi(string(buf[0 : len(buf)-1])) return val / 4, err } @@ -370,7 +372,10 @@ func (c *Adaptor) newUnexportedDigitalPin(i int, o ...func(gobot.DigitalPinOptio return io.Unexport() } -func (c *Adaptor) newExportedDigitalPin(pin int, o ...func(gobot.DigitalPinOptioner) bool) (gobot.DigitalPinner, error) { +func (c *Adaptor) newExportedDigitalPin( + pin int, + o ...func(gobot.DigitalPinOptioner) bool, +) (gobot.DigitalPinner, error) { sysPin := c.sys.NewDigitalPin("", pin, o...) err := sysPin.Export() return sysPin, err @@ -387,10 +392,10 @@ func (c *Adaptor) changePinMode(pin, mode string) error { return err } -func (c *Adaptor) digitalWrite(pin string, val byte) (err error) { +func (c *Adaptor) digitalWrite(pin string, val byte) error { sysPin, err := c.digitalPin(pin, system.WithPinDirectionOutput(int(val))) if err != nil { - return + return err } return sysPin.Write(int(val)) } diff --git a/platforms/intel-iot/edison/edison_adaptor_test.go b/platforms/intel-iot/edison/edison_adaptor_test.go index 64a2a7b6e..6709d9991 100644 --- a/platforms/intel-iot/edison/edison_adaptor_test.go +++ b/platforms/intel-iot/edison/edison_adaptor_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/aio" "gobot.io/x/gobot/v2/drivers/gpio" @@ -244,7 +245,7 @@ func TestArduinoSetupFail263(t *testing.T) { delete(fs.Files, "/sys/class/gpio/gpio263/direction") err := a.arduinoSetup() - assert.Contains(t, err.Error(), "/sys/class/gpio/gpio263/direction: no such file") + require.ErrorContains(t, err, "/sys/class/gpio/gpio263/direction: no such file") } func TestArduinoSetupFail240(t *testing.T) { @@ -252,7 +253,7 @@ func TestArduinoSetupFail240(t *testing.T) { delete(fs.Files, "/sys/class/gpio/gpio240/direction") err := a.arduinoSetup() - assert.Contains(t, err.Error(), "/sys/class/gpio/gpio240/direction: no such file") + require.ErrorContains(t, err, "/sys/class/gpio/gpio240/direction: no such file") } func TestArduinoSetupFail111(t *testing.T) { @@ -260,7 +261,7 @@ func TestArduinoSetupFail111(t *testing.T) { delete(fs.Files, "/sys/kernel/debug/gpio_debug/gpio111/current_pinmux") err := a.arduinoSetup() - assert.Contains(t, err.Error(), "/sys/kernel/debug/gpio_debug/gpio111/current_pinmux: no such file") + require.ErrorContains(t, err, "/sys/kernel/debug/gpio_debug/gpio111/current_pinmux: no such file") } func TestArduinoSetupFail131(t *testing.T) { @@ -268,7 +269,7 @@ func TestArduinoSetupFail131(t *testing.T) { delete(fs.Files, "/sys/kernel/debug/gpio_debug/gpio131/current_pinmux") err := a.arduinoSetup() - assert.Contains(t, err.Error(), "/sys/kernel/debug/gpio_debug/gpio131/current_pinmux: no such file") + require.ErrorContains(t, err, "/sys/kernel/debug/gpio_debug/gpio131/current_pinmux: no such file") } func TestArduinoI2CSetupFailTristate(t *testing.T) { @@ -287,7 +288,7 @@ func TestArduinoI2CSetupFail14(t *testing.T) { delete(fs.Files, "/sys/class/gpio/gpio14/direction") err := a.arduinoI2CSetup() - assert.Contains(t, err.Error(), "/sys/class/gpio/gpio14/direction: no such file") + require.ErrorContains(t, err, "/sys/class/gpio/gpio14/direction: no such file") } func TestArduinoI2CSetupUnexportFail(t *testing.T) { @@ -297,7 +298,7 @@ func TestArduinoI2CSetupUnexportFail(t *testing.T) { delete(fs.Files, "/sys/class/gpio/unexport") err := a.arduinoI2CSetup() - assert.Contains(t, err.Error(), "/sys/class/gpio/unexport: no such file") + require.ErrorContains(t, err, "/sys/class/gpio/unexport: no such file") } func TestArduinoI2CSetupFail236(t *testing.T) { @@ -307,7 +308,7 @@ func TestArduinoI2CSetupFail236(t *testing.T) { delete(fs.Files, "/sys/class/gpio/gpio236/direction") err := a.arduinoI2CSetup() - assert.Contains(t, err.Error(), "/sys/class/gpio/gpio236/direction: no such file") + require.ErrorContains(t, err, "/sys/class/gpio/gpio236/direction: no such file") } func TestArduinoI2CSetupFail28(t *testing.T) { @@ -317,7 +318,7 @@ func TestArduinoI2CSetupFail28(t *testing.T) { delete(fs.Files, "/sys/kernel/debug/gpio_debug/gpio28/current_pinmux") err := a.arduinoI2CSetup() - assert.Contains(t, err.Error(), "/sys/kernel/debug/gpio_debug/gpio28/current_pinmux: no such file") + require.ErrorContains(t, err, "/sys/kernel/debug/gpio_debug/gpio28/current_pinmux: no such file") } func TestConnectArduinoError(t *testing.T) { @@ -325,7 +326,7 @@ func TestConnectArduinoError(t *testing.T) { fs.WithWriteError = true err := a.Connect() - assert.Contains(t, err.Error(), "write error") + require.ErrorContains(t, err, "write error") } func TestConnectArduinoWriteError(t *testing.T) { @@ -333,7 +334,7 @@ func TestConnectArduinoWriteError(t *testing.T) { fs.WithWriteError = true err := a.Connect() - assert.Contains(t, err.Error(), "write error") + require.ErrorContains(t, err, "write error") } func TestConnectSparkfun(t *testing.T) { @@ -356,7 +357,7 @@ func TestConnectUnknown(t *testing.T) { a := NewAdaptor("wha") err := a.Connect() - assert.Contains(t, err.Error(), "Unknown board type: wha") + require.ErrorContains(t, err, "Unknown board type: wha") } func TestFinalize(t *testing.T) { @@ -376,8 +377,8 @@ func TestFinalize(t *testing.T) { // remove one file to force Finalize error delete(fs.Files, "/sys/class/gpio/unexport") err := a.Finalize() - assert.Contains(t, err.Error(), "1 error occurred") - assert.Contains(t, err.Error(), "/sys/class/gpio/unexport") + require.ErrorContains(t, err, "1 error occurred") + require.ErrorContains(t, err, "/sys/class/gpio/unexport") } func TestFinalizeError(t *testing.T) { @@ -387,10 +388,10 @@ func TestFinalizeError(t *testing.T) { fs.WithWriteError = true err := a.Finalize() - assert.Contains(t, err.Error(), "6 errors occurred") - assert.Contains(t, err.Error(), "write error") - assert.Contains(t, err.Error(), "SetEnabled(false) failed for id 1 with write error") - assert.Contains(t, err.Error(), "Unexport() failed for id 1 with write error") + require.ErrorContains(t, err, "6 errors occurred") + require.ErrorContains(t, err, "write error") + require.ErrorContains(t, err, "SetEnabled(false) failed for id 1 with write error") + require.ErrorContains(t, err, "Unexport() failed for id 1 with write error") } func TestDigitalIO(t *testing.T) { @@ -413,7 +414,7 @@ func TestDigitalPinInFileError(t *testing.T) { _ = a.Connect() _, err := a.DigitalPin("13") - assert.Contains(t, err.Error(), "no such file") + require.ErrorContains(t, err, "no such file") } func TestDigitalPinInResistorFileError(t *testing.T) { @@ -424,7 +425,7 @@ func TestDigitalPinInResistorFileError(t *testing.T) { _ = a.Connect() _, err := a.DigitalPin("13") - assert.Contains(t, err.Error(), "no such file") + require.ErrorContains(t, err, "no such file") } func TestDigitalPinInLevelShifterFileError(t *testing.T) { @@ -435,7 +436,7 @@ func TestDigitalPinInLevelShifterFileError(t *testing.T) { _ = a.Connect() _, err := a.DigitalPin("13") - assert.Contains(t, err.Error(), "no such file") + require.ErrorContains(t, err, "no such file") } func TestDigitalPinInMuxFileError(t *testing.T) { @@ -446,7 +447,7 @@ func TestDigitalPinInMuxFileError(t *testing.T) { _ = a.Connect() _, err := a.DigitalPin("13") - assert.Contains(t, err.Error(), "no such file") + require.ErrorContains(t, err, "no such file") } func TestDigitalWriteError(t *testing.T) { @@ -484,7 +485,7 @@ func TestPwmExportError(t *testing.T) { require.NoError(t, err) err = a.PwmWrite("5", 100) - assert.Contains(t, err.Error(), "/sys/class/pwm/pwmchip0/export: no such file") + require.ErrorContains(t, err, "/sys/class/pwm/pwmchip0/export: no such file") } func TestPwmEnableError(t *testing.T) { @@ -494,7 +495,7 @@ func TestPwmEnableError(t *testing.T) { _ = a.Connect() err := a.PwmWrite("5", 100) - assert.Contains(t, err.Error(), "/sys/class/pwm/pwmchip0/pwm1/enable: no such file") + require.ErrorContains(t, err, "/sys/class/pwm/pwmchip0/pwm1/enable: no such file") } func TestPwmWritePinError(t *testing.T) { @@ -510,7 +511,7 @@ func TestPwmWriteError(t *testing.T) { fs.WithWriteError = true err := a.PwmWrite("5", 100) - assert.Contains(t, err.Error(), "write error") + require.ErrorContains(t, err, "write error") } func TestPwmReadError(t *testing.T) { @@ -518,7 +519,7 @@ func TestPwmReadError(t *testing.T) { fs.WithReadError = true err := a.PwmWrite("5", 100) - assert.Contains(t, err.Error(), "read error") + require.ErrorContains(t, err, "read error") } func TestAnalog(t *testing.T) { @@ -570,7 +571,7 @@ func TestI2cFinalizeWithErrors(t *testing.T) { err = a.Finalize() // assert require.Error(t, err) - assert.Contains(t, err.Error(), "close error") + require.ErrorContains(t, err, "close error") } func Test_validateI2cBusNumber(t *testing.T) { diff --git a/platforms/intel-iot/joule/joule_adaptor.go b/platforms/intel-iot/joule/joule_adaptor.go index 3de700344..0afdc83d5 100644 --- a/platforms/intel-iot/joule/joule_adaptor.go +++ b/platforms/intel-iot/joule/joule_adaptor.go @@ -5,6 +5,7 @@ import ( "sync" multierror "github.com/hashicorp/go-multierror" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/platforms/adaptors" "gobot.io/x/gobot/v2/system" @@ -40,7 +41,8 @@ func NewAdaptor(opts ...func(adaptors.Optioner)) *Adaptor { sys: sys, } c.DigitalPinsAdaptor = adaptors.NewDigitalPinsAdaptor(sys, c.translateDigitalPin, opts...) - c.PWMPinsAdaptor = adaptors.NewPWMPinsAdaptor(sys, c.translatePWMPin, adaptors.WithPWMPinInitializer(pwmPinInitializer)) + c.PWMPinsAdaptor = adaptors.NewPWMPinsAdaptor(sys, c.translatePWMPin, + adaptors.WithPWMPinInitializer(pwmPinInitializer)) c.I2cBusAdaptor = adaptors.NewI2cBusAdaptor(sys, c.validateI2cBusNumber, defaultI2cBusNumber) return c } diff --git a/platforms/intel-iot/joule/joule_adaptor_test.go b/platforms/intel-iot/joule/joule_adaptor_test.go index 21896a35d..fa159a4ab 100644 --- a/platforms/intel-iot/joule/joule_adaptor_test.go +++ b/platforms/intel-iot/joule/joule_adaptor_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/gpio" "gobot.io/x/gobot/v2/drivers/i2c" @@ -156,7 +157,7 @@ func TestPwmPinExportError(t *testing.T) { delete(fs.Files, "/sys/class/pwm/pwmchip0/export") err := a.PwmWrite("J12_26", 100) - assert.Contains(t, err.Error(), "/sys/class/pwm/pwmchip0/export: no such file") + require.ErrorContains(t, err, "/sys/class/pwm/pwmchip0/export: no such file") } func TestPwmPinEnableError(t *testing.T) { @@ -164,7 +165,7 @@ func TestPwmPinEnableError(t *testing.T) { delete(fs.Files, "/sys/class/pwm/pwmchip0/pwm0/enable") err := a.PwmWrite("J12_26", 100) - assert.Contains(t, err.Error(), "/sys/class/pwm/pwmchip0/pwm0/enable: no such file") + require.ErrorContains(t, err, "/sys/class/pwm/pwmchip0/pwm0/enable: no such file") } func TestI2cDefaultBus(t *testing.T) { @@ -186,7 +187,7 @@ func TestI2cFinalizeWithErrors(t *testing.T) { // act err = a.Finalize() // assert - assert.Contains(t, err.Error(), "close error") + require.ErrorContains(t, err, "close error") } func Test_validateI2cBusNumber(t *testing.T) { diff --git a/platforms/jetson/jetson_adaptor.go b/platforms/jetson/jetson_adaptor.go index c0e25b4c4..ce336ed34 100644 --- a/platforms/jetson/jetson_adaptor.go +++ b/platforms/jetson/jetson_adaptor.go @@ -6,6 +6,7 @@ import ( "sync" multierror "github.com/hashicorp/go-multierror" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/platforms/adaptors" "gobot.io/x/gobot/v2/system" @@ -121,7 +122,7 @@ func (c *Adaptor) PWMPin(pin string) (gobot.PWMPinner, error) { } // PwmWrite writes a PWM signal to the specified pin -func (c *Adaptor) PwmWrite(pin string, val byte) (err error) { +func (c *Adaptor) PwmWrite(pin string, val byte) error { c.mutex.Lock() defer c.mutex.Unlock() @@ -135,7 +136,7 @@ func (c *Adaptor) PwmWrite(pin string, val byte) (err error) { } // ServoWrite writes a servo signal to the specified pin -func (c *Adaptor) ServoWrite(pin string, angle byte) (err error) { +func (c *Adaptor) ServoWrite(pin string, angle byte) error { c.mutex.Lock() defer c.mutex.Unlock() @@ -200,7 +201,7 @@ func (c *Adaptor) translateDigitalPin(id string) (string, int, error) { return "", -1, fmt.Errorf("'%s' is not a valid id for a digital pin", id) } -func (c *Adaptor) translatePwmPin(pin string) (fn string, err error) { +func (c *Adaptor) translatePwmPin(pin string) (string, error) { if fn, ok := pwmPins[pin]; ok { return fn, nil } diff --git a/platforms/jetson/jetson_adaptor_test.go b/platforms/jetson/jetson_adaptor_test.go index dd74c8327..11c9e3338 100644 --- a/platforms/jetson/jetson_adaptor_test.go +++ b/platforms/jetson/jetson_adaptor_test.go @@ -10,6 +10,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/gpio" "gobot.io/x/gobot/v2/drivers/i2c" @@ -173,7 +174,7 @@ func TestI2cFinalizeWithErrors(t *testing.T) { // act err = a.Finalize() // assert - assert.Contains(t, err.Error(), "close error") + require.ErrorContains(t, err, "close error") } func Test_validateSpiBusNumber(t *testing.T) { diff --git a/platforms/jetson/pwm_pin.go b/platforms/jetson/pwm_pin.go index 78f1ad407..558e832ef 100644 --- a/platforms/jetson/pwm_pin.go +++ b/platforms/jetson/pwm_pin.go @@ -73,7 +73,7 @@ func (p *PWMPin) SetPolarity(bool) error { } // Period returns the cached PWM period for pin -func (p *PWMPin) Period() (period uint32, err error) { +func (p *PWMPin) Period() (uint32, error) { if p.period == 0 { return p.period, errors.New("Jetson PWM pin period not set") } diff --git a/platforms/joystick/joystick_adaptor.go b/platforms/joystick/joystick_adaptor.go index fba07f6bd..38de67587 100644 --- a/platforms/joystick/joystick_adaptor.go +++ b/platforms/joystick/joystick_adaptor.go @@ -4,9 +4,9 @@ import ( "fmt" "strconv" - "gobot.io/x/gobot/v2" - js "github.com/0xcafed00d/joystick" + + "gobot.io/x/gobot/v2" ) // Adaptor represents a connection to a joystick @@ -25,12 +25,12 @@ func NewAdaptor(id string) *Adaptor { connect: func(j *Adaptor) error { i, err := strconv.Atoi(id) if err != nil { - return fmt.Errorf("Invalid joystick ID: %v", err) + return fmt.Errorf("invalid joystick ID: %v", err) } joy, err := js.Open(i) if err != nil { - return fmt.Errorf("No joystick available: %v", err) + return fmt.Errorf("no joystick available: %v", err) } j.id = id diff --git a/platforms/joystick/joystick_adaptor_test.go b/platforms/joystick/joystick_adaptor_test.go index c638bd201..8ae984dd0 100644 --- a/platforms/joystick/joystick_adaptor_test.go +++ b/platforms/joystick/joystick_adaptor_test.go @@ -14,7 +14,7 @@ var _ gobot.Adaptor = (*Adaptor)(nil) func initTestAdaptor() *Adaptor { a := NewAdaptor("6") - a.connect = func(j *Adaptor) (err error) { + a.connect = func(j *Adaptor) error { j.joystick = &testJoystick{} return nil } @@ -34,7 +34,7 @@ func TestAdaptorConnect(t *testing.T) { a = NewAdaptor("6") err := a.Connect() - assert.True(t, strings.HasPrefix(err.Error(), "No joystick available")) + require.ErrorContains(t, err, "no joystick available") } func TestAdaptorFinalize(t *testing.T) { diff --git a/platforms/joystick/joystick_driver.go b/platforms/joystick/joystick_driver.go index c313f362d..3af42505e 100644 --- a/platforms/joystick/joystick_driver.go +++ b/platforms/joystick/joystick_driver.go @@ -7,6 +7,7 @@ import ( "time" js "github.com/0xcafed00d/joystick" + "gobot.io/x/gobot/v2" ) @@ -106,6 +107,7 @@ func (j *Driver) Connection() gobot.Connection { return j.connection } // adaptor returns joystick adaptor func (j *Driver) adaptor() *Adaptor { + //nolint:forcetypeassert // ok here return j.Connection().(*Adaptor) } @@ -196,9 +198,9 @@ func (j *Driver) initEvents() { } // Halt stops joystick driver -func (j *Driver) Halt() (err error) { +func (j *Driver) Halt() error { j.halt <- true - return + return nil } func (j *Driver) handleButtons(state js.State) error { diff --git a/platforms/joystick/joystick_driver_test.go b/platforms/joystick/joystick_driver_test.go index 87996fc28..48965d3db 100644 --- a/platforms/joystick/joystick_driver_test.go +++ b/platforms/joystick/joystick_driver_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert // ok here package joystick import ( @@ -5,12 +6,11 @@ import ( "testing" "time" + js "github.com/0xcafed00d/joystick" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "gobot.io/x/gobot/v2" - - js "github.com/0xcafed00d/joystick" ) var _ gobot.Driver = (*Driver)(nil) @@ -18,7 +18,7 @@ var _ gobot.Driver = (*Driver)(nil) func initTestDriver(config string) (*Driver, *testJoystick) { a := NewAdaptor("6") tj := &testJoystick{} - a.connect = func(j *Adaptor) (err error) { + a.connect = func(j *Adaptor) error { j.joystick = tj return nil } @@ -220,5 +220,5 @@ func TestDriverHandleEventDS4(t *testing.T) { func TestDriverInvalidConfig(t *testing.T) { d, _ := initTestDriver("./configs/doesnotexist") err := d.Start() - assert.Contains(t, err.Error(), "loadfile error") + require.ErrorContains(t, err, "loadfile error") } diff --git a/platforms/keyboard/keyboard.go b/platforms/keyboard/keyboard.go index 8ad037d90..3ee0bb311 100644 --- a/platforms/keyboard/keyboard.go +++ b/platforms/keyboard/keyboard.go @@ -148,7 +148,7 @@ func Parse(input bytes) KeyEvent { } // fetches original state, sets up TTY for raw (unbuffered) input -func configure() (err error) { +func configure() error { state, err := stty("-g") if err != nil { return err @@ -158,24 +158,20 @@ func configure() (err error) { // -echo: terminal doesn't echo typed characters back to the terminal // -icanon: terminal doesn't interpret special characters (like backspace) - if _, err := stty("-echo", "-icanon"); err != nil { - return err - } + _, err = stty("-echo", "-icanon") - return + return err } // restores the TTY to the original state -func restore() (err error) { - if _, err = stty("echo"); err != nil { - return +func restore() error { + if _, err := stty("echo"); err != nil { + return err } - if _, err = stty(originalState); err != nil { - return - } + _, err := stty(originalState) - return + return err } func stty(args ...string) (string, error) { diff --git a/platforms/keyboard/keyboard_driver_test.go b/platforms/keyboard/keyboard_driver_test.go index 0d3500ac1..dada390ea 100644 --- a/platforms/keyboard/keyboard_driver_test.go +++ b/platforms/keyboard/keyboard_driver_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -14,7 +15,7 @@ var _ gobot.Driver = (*Driver)(nil) func initTestKeyboardDriver() *Driver { d := NewDriver() - d.connect = func(k *Driver) (err error) { + d.connect = func(k *Driver) error { k.stdin = &os.File{} return nil } diff --git a/platforms/leap/leap_motion_adaptor.go b/platforms/leap/leap_motion_adaptor.go index e78ae8054..78e2fa26f 100644 --- a/platforms/leap/leap_motion_adaptor.go +++ b/platforms/leap/leap_motion_adaptor.go @@ -3,9 +3,9 @@ package leap import ( "io" - "gobot.io/x/gobot/v2" - "golang.org/x/net/websocket" + + "gobot.io/x/gobot/v2" ) // Adaptor is the Gobot Adaptor connection to the Leap Motion @@ -38,15 +38,15 @@ func (l *Adaptor) SetName(n string) { l.name = n } func (l *Adaptor) Port() string { return l.port } // Connect returns true if connection to leap motion is established successfully -func (l *Adaptor) Connect() (err error) { - ws, e := l.connect(l.Port()) - if e != nil { - return e +func (l *Adaptor) Connect() error { + ws, err := l.connect(l.Port()) + if err != nil { + return err } l.ws = ws - return + return nil } // Finalize ends connection to leap motion -func (l *Adaptor) Finalize() (err error) { return } +func (l *Adaptor) Finalize() error { return nil } diff --git a/platforms/leap/leap_motion_adaptor_test.go b/platforms/leap/leap_motion_adaptor_test.go index b16018480..9f2d473d9 100644 --- a/platforms/leap/leap_motion_adaptor_test.go +++ b/platforms/leap/leap_motion_adaptor_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/leap/leap_motion_driver.go b/platforms/leap/leap_motion_driver.go index f420d475f..c7b8effb1 100644 --- a/platforms/leap/leap_motion_driver.go +++ b/platforms/leap/leap_motion_driver.go @@ -5,8 +5,9 @@ import ( "io" "log" - "gobot.io/x/gobot/v2" "golang.org/x/net/websocket" + + "gobot.io/x/gobot/v2" ) const ( @@ -39,6 +40,7 @@ func NewDriver(a *Adaptor) *Driver { connection: a, Eventer: gobot.NewEventer(), receive: func(ws io.ReadWriteCloser, msg *[]byte) { + //nolint:forcetypeassert // ok here if err := websocket.Message.Receive(ws.(*websocket.Conn), msg); err != nil { panic(err) } @@ -62,6 +64,7 @@ func (l *Driver) Connection() gobot.Connection { return l.connection } // adaptor returns leap motion adaptor func (l *Driver) adaptor() *Adaptor { + //nolint:forcetypeassert // ok here return l.Connection().(*Adaptor) } diff --git a/platforms/leap/leap_motion_driver_test.go b/platforms/leap/leap_motion_driver_test.go index 7d6a43f8c..f7ecb0f5b 100644 --- a/platforms/leap/leap_motion_driver_test.go +++ b/platforms/leap/leap_motion_driver_test.go @@ -10,6 +10,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/mavlink/common/common.go b/platforms/mavlink/common/common.go index 4f8133186..2b3dbca7a 100644 --- a/platforms/mavlink/common/common.go +++ b/platforms/mavlink/common/common.go @@ -1,3 +1,4 @@ +//nolint:dupl,gocritic,lll // seems to be useful here package mavlink // diff --git a/platforms/mavlink/common/mavlink.go b/platforms/mavlink/common/mavlink.go index 2d794e8c3..ae99c4dbd 100644 --- a/platforms/mavlink/common/mavlink.go +++ b/platforms/mavlink/common/mavlink.go @@ -80,28 +80,36 @@ func ReadMAVLinkPacket(r io.Reader) (*MAVLinkPacket, error) { } // CraftMAVLinkPacket returns a new MAVLinkPacket from a MAVLinkMessage -func CraftMAVLinkPacket(SystemID uint8, ComponentID uint8, Message MAVLinkMessage) *MAVLinkPacket { +func CraftMAVLinkPacket(systemID uint8, cComponentID uint8, mMessage MAVLinkMessage) *MAVLinkPacket { return NewMAVLinkPacket( 0xFE, - Message.Len(), + mMessage.Len(), generateSequence(), - SystemID, - ComponentID, - Message.Id(), - Message.Pack(), + systemID, + cComponentID, + mMessage.Id(), + mMessage.Pack(), ) } // NewMAVLinkPacket returns a new MAVLinkPacket -func NewMAVLinkPacket(Protocol uint8, Length uint8, Sequence uint8, SystemID uint8, ComponentID uint8, MessageID uint8, Data []uint8) *MAVLinkPacket { +func NewMAVLinkPacket( + pProtocol uint8, + lLength uint8, + sSequence uint8, + sSystemID uint8, + cComponentID uint8, + mMessageID uint8, + dData []uint8, +) *MAVLinkPacket { m := &MAVLinkPacket{ - Protocol: Protocol, - Length: Length, - Sequence: Sequence, - SystemID: SystemID, - ComponentID: ComponentID, - MessageID: MessageID, - Data: Data, + Protocol: pProtocol, + Length: lLength, + Sequence: sSequence, + SystemID: sSystemID, + ComponentID: cComponentID, + MessageID: mMessageID, + Data: dData, } m.Checksum = crcCalculate(m) return m @@ -158,7 +166,7 @@ func read(r io.Reader, length int) ([]byte, error) { buf := []byte{} for length > 0 { tmp := make([]byte, length) - i, err := r.Read(tmp[:]) + i, err := r.Read(tmp) if err != nil { return nil, err } diff --git a/platforms/mavlink/mavlink_adaptor.go b/platforms/mavlink/mavlink_adaptor.go index ee0ae4116..4a1792677 100644 --- a/platforms/mavlink/mavlink_adaptor.go +++ b/platforms/mavlink/mavlink_adaptor.go @@ -4,6 +4,7 @@ import ( "io" "go.bug.st/serial" + "gobot.io/x/gobot/v2" common "gobot.io/x/gobot/v2/platforms/mavlink/common" ) @@ -40,19 +41,19 @@ func (m *Adaptor) SetName(n string) { m.name = n } func (m *Adaptor) Port() string { return m.port } // Connect returns true if connection to device is successful -func (m *Adaptor) Connect() (err error) { - if sp, e := m.connect(m.Port()); e != nil { - return e - } else { - m.sp = sp +func (m *Adaptor) Connect() error { + sp, err := m.connect(m.Port()) + if err != nil { + return err } - return + m.sp = sp + + return nil } // Finalize returns true if connection to devices is closed successfully -func (m *Adaptor) Finalize() (err error) { - err = m.sp.Close() - return +func (m *Adaptor) Finalize() error { + return m.sp.Close() } func (m *Adaptor) ReadMAVLinkPacket() (*common.MAVLinkPacket, error) { diff --git a/platforms/mavlink/mavlink_adaptor_test.go b/platforms/mavlink/mavlink_adaptor_test.go index 2c71068e0..da18a6c93 100644 --- a/platforms/mavlink/mavlink_adaptor_test.go +++ b/platforms/mavlink/mavlink_adaptor_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -15,7 +16,9 @@ var _ gobot.Adaptor = (*Adaptor)(nil) type nullReadWriteCloser struct{} -var payload = []byte{0xFE, 0x09, 0x4E, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x03, 0x51, 0x04, 0x03, 0x1C, 0x7F} +var payload = []byte{ + 0xFE, 0x09, 0x4E, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x03, 0x51, 0x04, 0x03, 0x1C, 0x7F, +} var testAdaptorRead = func(p []byte) (int, error) { return len(p), nil diff --git a/platforms/mavlink/mavlink_driver.go b/platforms/mavlink/mavlink_driver.go index d4330633d..7a361615d 100644 --- a/platforms/mavlink/mavlink_driver.go +++ b/platforms/mavlink/mavlink_driver.go @@ -59,6 +59,7 @@ func (m *Driver) SetName(n string) { m.name = n } // adaptor returns driver associated adaptor func (m *Driver) adaptor() BaseAdaptor { + //nolint:forcetypeassert // ok here return m.Connection().(BaseAdaptor) } @@ -86,10 +87,10 @@ func (m *Driver) Start() error { } // Halt returns true if device is halted successfully -func (m *Driver) Halt() (err error) { return } +func (m *Driver) Halt() error { return nil } // SendPacket sends a packet to mavlink device -func (m *Driver) SendPacket(packet *common.MAVLinkPacket) (err error) { - _, err = m.adaptor().Write(packet.Pack()) +func (m *Driver) SendPacket(packet *common.MAVLinkPacket) error { + _, err := m.adaptor().Write(packet.Pack()) return err } diff --git a/platforms/mavlink/mavlink_driver_test.go b/platforms/mavlink/mavlink_driver_test.go index a357181d4..abc0a675e 100644 --- a/platforms/mavlink/mavlink_driver_test.go +++ b/platforms/mavlink/mavlink_driver_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert // ok here package mavlink import ( @@ -8,6 +9,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" common "gobot.io/x/gobot/v2/platforms/mavlink/common" ) diff --git a/platforms/mavlink/mavlink_udp_adaptor.go b/platforms/mavlink/mavlink_udp_adaptor.go index f4cb22e50..47d7a169a 100644 --- a/platforms/mavlink/mavlink_udp_adaptor.go +++ b/platforms/mavlink/mavlink_udp_adaptor.go @@ -61,7 +61,7 @@ func (m *UDPAdaptor) close() error { } // Finalize returns true if connection to devices is closed successfully -func (m *UDPAdaptor) Finalize() (err error) { +func (m *UDPAdaptor) Finalize() error { return m.close() } diff --git a/platforms/mavlink/mavlink_udp_adaptor_test.go b/platforms/mavlink/mavlink_udp_adaptor_test.go index 513eca2db..c5bf6e515 100644 --- a/platforms/mavlink/mavlink_udp_adaptor_test.go +++ b/platforms/mavlink/mavlink_udp_adaptor_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" mavlink "gobot.io/x/gobot/v2/platforms/mavlink/common" ) diff --git a/platforms/megapi/megapi_adaptor.go b/platforms/megapi/megapi_adaptor.go index bdbf61063..fb8767e44 100644 --- a/platforms/megapi/megapi_adaptor.go +++ b/platforms/megapi/megapi_adaptor.go @@ -5,6 +5,7 @@ import ( "time" "go.bug.st/serial" + "gobot.io/x/gobot/v2" ) @@ -20,7 +21,7 @@ type Adaptor struct { finalizeChannel chan struct{} } -// NewAdaptor returns a new MegaPi Adaptor with specified serial port used to talk to the MegaPi with a baud rate of 115200 +// NewAdaptor returns a new Adaptor with specified serial port used to talk to the MegaPi with a baud rate of 115200 func NewAdaptor(device string) *Adaptor { c := &serial.Mode{BaudRate: 115200} return &Adaptor{ diff --git a/platforms/megapi/motor_driver.go b/platforms/megapi/motor_driver.go index 1efce6f9a..ff6709cdf 100644 --- a/platforms/megapi/motor_driver.go +++ b/platforms/megapi/motor_driver.go @@ -31,67 +31,67 @@ func NewMotorDriver(megaPi *Adaptor, port byte) *MotorDriver { } // Name returns the name of this motor -func (m *MotorDriver) Name() string { - return m.name +func (d *MotorDriver) Name() string { + return d.name } // SetName sets the name of this motor -func (m *MotorDriver) SetName(n string) { - m.name = n +func (d *MotorDriver) SetName(n string) { + d.name = n } // Start implements the Driver interface -func (m *MotorDriver) Start() error { - m.syncRoot.Lock() - defer m.syncRoot.Unlock() - m.halted = false - return m.speedHelper(0) +func (d *MotorDriver) Start() error { + d.syncRoot.Lock() + defer d.syncRoot.Unlock() + d.halted = false + return d.speedHelper(0) } // Halt terminates the Driver interface -func (m *MotorDriver) Halt() error { - m.syncRoot.Lock() - defer m.syncRoot.Unlock() - m.halted = true - return m.speedHelper(0) +func (d *MotorDriver) Halt() error { + d.syncRoot.Lock() + defer d.syncRoot.Unlock() + d.halted = true + return d.speedHelper(0) } // Connection returns the Connection associated with the Driver -func (m *MotorDriver) Connection() gobot.Connection { - return gobot.Connection(m.megaPi) +func (d *MotorDriver) Connection() gobot.Connection { + return gobot.Connection(d.megaPi) } // Speed sets the motors speed to the specified value -func (m *MotorDriver) Speed(speed int16) error { - m.syncRoot.Lock() - defer m.syncRoot.Unlock() - if m.halted { +func (d *MotorDriver) Speed(speed int16) error { + d.syncRoot.Lock() + defer d.syncRoot.Unlock() + if d.halted { return nil } - return m.speedHelper(speed) + return d.speedHelper(speed) } // there is some sort of bug on the hardware such that you cannot // send the exact same speed to 2 different motors consecutively // hence we ensure we always alternate speeds -func (m *MotorDriver) speedHelper(speed int16) error { - if err := m.sendSpeed(speed - 1); err != nil { +func (d *MotorDriver) speedHelper(speed int16) error { + if err := d.sendSpeed(speed - 1); err != nil { return err } - return m.sendSpeed(speed) + return d.sendSpeed(speed) } // sendSpeed sets the motors speed to the specified value -func (m *MotorDriver) sendSpeed(speed int16) error { +func (d *MotorDriver) sendSpeed(speed int16) error { bufOut := new(bytes.Buffer) // byte sequence: 0xff, 0x55, id, action, device, port - bufOut.Write([]byte{0xff, 0x55, 0x6, 0x0, 0x2, 0xa, m.port}) + bufOut.Write([]byte{0xff, 0x55, 0x6, 0x0, 0x2, 0xa, d.port}) if err := binary.Write(bufOut, binary.LittleEndian, speed); err != nil { return err } bufOut.Write([]byte{0xa}) - m.megaPi.writeBytesChannel <- bufOut.Bytes() + d.megaPi.writeBytesChannel <- bufOut.Bytes() return nil } diff --git a/platforms/microbit/accelerometer_driver.go b/platforms/microbit/accelerometer_driver.go index 97b26ad89..76dda8fc3 100644 --- a/platforms/microbit/accelerometer_driver.go +++ b/platforms/microbit/accelerometer_driver.go @@ -62,6 +62,7 @@ func (b *AccelerometerDriver) SetName(n string) { b.name = n } // adaptor returns BLE adaptor func (b *AccelerometerDriver) adaptor() ble.BLEConnector { + //nolint:forcetypeassert // ok here return b.Connection().(ble.BLEConnector) } diff --git a/platforms/microbit/accelerometer_driver_test.go b/platforms/microbit/accelerometer_driver_test.go index 312edc23d..33ea547a5 100644 --- a/platforms/microbit/accelerometer_driver_test.go +++ b/platforms/microbit/accelerometer_driver_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert,dupl // ok here package microbit import ( @@ -7,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/microbit/button_driver.go b/platforms/microbit/button_driver.go index 3fc779329..35a17bbfb 100644 --- a/platforms/microbit/button_driver.go +++ b/platforms/microbit/button_driver.go @@ -52,6 +52,7 @@ func (b *ButtonDriver) SetName(n string) { b.name = n } // adaptor returns BLE adaptor func (b *ButtonDriver) adaptor() ble.BLEConnector { + //nolint:forcetypeassert // ok here return b.Connection().(ble.BLEConnector) } diff --git a/platforms/microbit/button_driver_test.go b/platforms/microbit/button_driver_test.go index 6af815e8d..be92c0ed7 100644 --- a/platforms/microbit/button_driver_test.go +++ b/platforms/microbit/button_driver_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/microbit/helpers_test.go b/platforms/microbit/helpers_test.go index 8c94a9615..acf446f2d 100644 --- a/platforms/microbit/helpers_test.go +++ b/platforms/microbit/helpers_test.go @@ -19,30 +19,30 @@ type bleTestClientAdaptor struct { testWriteCharacteristic func(string, []byte) error } -func (t *bleTestClientAdaptor) Connect() (err error) { return } -func (t *bleTestClientAdaptor) Reconnect() (err error) { return } -func (t *bleTestClientAdaptor) Disconnect() (err error) { return } -func (t *bleTestClientAdaptor) Finalize() (err error) { return } +func (t *bleTestClientAdaptor) Connect() error { return nil } +func (t *bleTestClientAdaptor) Reconnect() error { return nil } +func (t *bleTestClientAdaptor) Disconnect() error { return nil } +func (t *bleTestClientAdaptor) Finalize() error { return nil } func (t *bleTestClientAdaptor) Name() string { return t.name } func (t *bleTestClientAdaptor) SetName(n string) { t.name = n } func (t *bleTestClientAdaptor) Address() string { return t.address } func (t *bleTestClientAdaptor) WithoutResponses(use bool) { t.withoutResponses = use } -func (t *bleTestClientAdaptor) ReadCharacteristic(cUUID string) (data []byte, err error) { +func (t *bleTestClientAdaptor) ReadCharacteristic(cUUID string) ([]byte, error) { t.mtx.Lock() defer t.mtx.Unlock() return t.testReadCharacteristic(cUUID) } -func (t *bleTestClientAdaptor) WriteCharacteristic(cUUID string, data []byte) (err error) { +func (t *bleTestClientAdaptor) WriteCharacteristic(cUUID string, data []byte) error { t.mtx.Lock() defer t.mtx.Unlock() return t.testWriteCharacteristic(cUUID, data) } -func (t *bleTestClientAdaptor) Subscribe(cUUID string, f func([]byte, error)) (err error) { +func (t *bleTestClientAdaptor) Subscribe(cUUID string, f func([]byte, error)) error { t.testSubscribe = f - return + return nil } func (t *bleTestClientAdaptor) TestReadCharacteristic(f func(cUUID string) (data []byte, err error)) { @@ -51,7 +51,7 @@ func (t *bleTestClientAdaptor) TestReadCharacteristic(f func(cUUID string) (data t.testReadCharacteristic = f } -func (t *bleTestClientAdaptor) TestWriteCharacteristic(f func(cUUID string, data []byte) (err error)) { +func (t *bleTestClientAdaptor) TestWriteCharacteristic(f func(cUUID string, data []byte) error) { t.mtx.Lock() defer t.mtx.Unlock() t.testWriteCharacteristic = f @@ -66,11 +66,11 @@ func (t *bleTestClientAdaptor) TestReceiveNotification(data []byte, err error) { func NewBleTestAdaptor() *bleTestClientAdaptor { return &bleTestClientAdaptor{ address: "01:02:03:04:05:06", - testReadCharacteristic: func(cUUID string) (data []byte, e error) { - return + testReadCharacteristic: func(cUUID string) ([]byte, error) { + return nil, nil }, - testWriteCharacteristic: func(cUUID string, data []byte) (e error) { - return + testWriteCharacteristic: func(cUUID string, data []byte) error { + return nil }, testSubscribe: func([]byte, error) {}, } diff --git a/platforms/microbit/io_pin_driver.go b/platforms/microbit/io_pin_driver.go index e9e4e51d6..b57a11027 100644 --- a/platforms/microbit/io_pin_driver.go +++ b/platforms/microbit/io_pin_driver.go @@ -58,6 +58,7 @@ func (b *IOPinDriver) SetName(n string) { b.name = n } // adaptor returns BLE adaptor func (b *IOPinDriver) adaptor() ble.BLEConnector { + //nolint:forcetypeassert // ok here return b.Connection().(ble.BLEConnector) } @@ -74,7 +75,7 @@ func (b *IOPinDriver) Start() error { func (b *IOPinDriver) Halt() error { return nil } // ReadAllPinData reads and returns the pin data for all pins -func (b *IOPinDriver) ReadAllPinData() (pins []PinData) { +func (b *IOPinDriver) ReadAllPinData() []PinData { c, _ := b.adaptor().ReadCharacteristic(pinDataCharacteristic) buf := bytes.NewBuffer(c) pinsData := make([]PinData, buf.Len()/2) diff --git a/platforms/microbit/io_pin_driver_test.go b/platforms/microbit/io_pin_driver_test.go index 21794606d..db8b3e158 100644 --- a/platforms/microbit/io_pin_driver_test.go +++ b/platforms/microbit/io_pin_driver_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/aio" "gobot.io/x/gobot/v2/drivers/gpio" diff --git a/platforms/microbit/led_driver.go b/platforms/microbit/led_driver.go index 80aca8cd8..83a42afe4 100644 --- a/platforms/microbit/led_driver.go +++ b/platforms/microbit/led_driver.go @@ -44,106 +44,90 @@ func (b *LEDDriver) SetName(n string) { b.name = n } // adaptor returns BLE adaptor func (b *LEDDriver) adaptor() ble.BLEConnector { + //nolint:forcetypeassert // ok here return b.Connection().(ble.BLEConnector) } // Start tells driver to get ready to do work -func (b *LEDDriver) Start() (err error) { - return -} +func (b *LEDDriver) Start() error { return nil } // Halt stops LED driver (void) -func (b *LEDDriver) Halt() (err error) { - return -} +func (b *LEDDriver) Halt() error { return nil } // ReadMatrix read the current LED matrix state -func (b *LEDDriver) ReadMatrix() (data []byte, err error) { - data, err = b.adaptor().ReadCharacteristic(ledMatrixStateCharacteristic) - return +func (b *LEDDriver) ReadMatrix() ([]byte, error) { + return b.adaptor().ReadCharacteristic(ledMatrixStateCharacteristic) } // WriteMatrix writes an array of 5 bytes to set the LED matrix -func (b *LEDDriver) WriteMatrix(data []byte) (err error) { - err = b.adaptor().WriteCharacteristic(ledMatrixStateCharacteristic, data) - return +func (b *LEDDriver) WriteMatrix(data []byte) error { + return b.adaptor().WriteCharacteristic(ledMatrixStateCharacteristic, data) } // WriteText writes a text message to the Microbit LED matrix -func (b *LEDDriver) WriteText(msg string) (err error) { - err = b.adaptor().WriteCharacteristic(ledTextCharacteristic, []byte(msg)) - return err +func (b *LEDDriver) WriteText(msg string) error { + return b.adaptor().WriteCharacteristic(ledTextCharacteristic, []byte(msg)) } -func (b *LEDDriver) ReadScrollingDelay() (delay uint16, err error) { - return +func (b *LEDDriver) ReadScrollingDelay() (uint16, error) { + return 0, nil } -func (b *LEDDriver) WriteScrollingDelay(delay uint16) (err error) { +func (b *LEDDriver) WriteScrollingDelay(delay uint16) error { buf := []byte{byte(delay)} - err = b.adaptor().WriteCharacteristic(ledScrollingDelayCharacteristic, buf) - return + return b.adaptor().WriteCharacteristic(ledScrollingDelayCharacteristic, buf) } // Blank clears the LEDs on the Microbit -func (b *LEDDriver) Blank() (err error) { +func (b *LEDDriver) Blank() error { buf := []byte{0x00, 0x00, 0x00, 0x00, 0x00} - err = b.WriteMatrix(buf) - return + return b.WriteMatrix(buf) } // Solid turns on all of the Microbit LEDs -func (b *LEDDriver) Solid() (err error) { +func (b *LEDDriver) Solid() error { buf := []byte{0x1F, 0x1F, 0x1F, 0x1F, 0x1F} - err = b.WriteMatrix(buf) - return + return b.WriteMatrix(buf) } // UpRightArrow displays an arrow pointing upwards and to the right on the Microbit LEDs -func (b *LEDDriver) UpRightArrow() (err error) { +func (b *LEDDriver) UpRightArrow() error { buf := []byte{0x0F, 0x03, 0x05, 0x09, 0x10} - err = b.WriteMatrix(buf) - return + return b.WriteMatrix(buf) } // UpLeftArrow displays an arrow pointing upwards and to the left on the Microbit LEDs -func (b *LEDDriver) UpLeftArrow() (err error) { +func (b *LEDDriver) UpLeftArrow() error { buf := []byte{0x1E, 0x18, 0x14, 0x12, 0x01} - err = b.WriteMatrix(buf) - return + return b.WriteMatrix(buf) } // DownRightArrow displays an arrow pointing down and to the right on the Microbit LEDs -func (b *LEDDriver) DownRightArrow() (err error) { +func (b *LEDDriver) DownRightArrow() error { buf := []byte{0x10, 0x09, 0x05, 0x03, 0x0F} - err = b.WriteMatrix(buf) - return + return b.WriteMatrix(buf) } // DownLeftArrow displays an arrow pointing down and to the left on the Microbit LEDs -func (b *LEDDriver) DownLeftArrow() (err error) { +func (b *LEDDriver) DownLeftArrow() error { buf := []byte{0x01, 0x12, 0x14, 0x18, 0x1E} - err = b.WriteMatrix(buf) - return + return b.WriteMatrix(buf) } // Dimond displays a dimond on the Microbit LEDs -func (b *LEDDriver) Dimond() (err error) { +func (b *LEDDriver) Dimond() error { buf := []byte{0x04, 0x0A, 0x11, 0x0A, 0x04} - err = b.WriteMatrix(buf) - return + return b.WriteMatrix(buf) } // Smile displays a smile on the Microbit LEDs -func (b *LEDDriver) Smile() (err error) { +func (b *LEDDriver) Smile() error { buf := []byte{0x0A, 0x0A, 0x00, 0x11, 0x0E} - err = b.WriteMatrix(buf) - return + return b.WriteMatrix(buf) } // Wink displays a wink on the Microbit LEDs -func (b *LEDDriver) Wink() (err error) { +func (b *LEDDriver) Wink() error { buf := []byte{0x08, 0x0B, 0x00, 0x11, 0x0E} - err = b.WriteMatrix(buf) - return + return b.WriteMatrix(buf) } diff --git a/platforms/microbit/led_driver_test.go b/platforms/microbit/led_driver_test.go index 5be9376a7..a59039dfb 100644 --- a/platforms/microbit/led_driver_test.go +++ b/platforms/microbit/led_driver_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/microbit/magnetometer_driver.go b/platforms/microbit/magnetometer_driver.go index c398eddc8..fa89d7403 100644 --- a/platforms/microbit/magnetometer_driver.go +++ b/platforms/microbit/magnetometer_driver.go @@ -62,6 +62,7 @@ func (b *MagnetometerDriver) SetName(n string) { b.name = n } // adaptor returns BLE adaptor func (b *MagnetometerDriver) adaptor() ble.BLEConnector { + //nolint:forcetypeassert // ok here return b.Connection().(ble.BLEConnector) } diff --git a/platforms/microbit/magnetometer_driver_test.go b/platforms/microbit/magnetometer_driver_test.go index 53a48f5f1..5a7d31f1f 100644 --- a/platforms/microbit/magnetometer_driver_test.go +++ b/platforms/microbit/magnetometer_driver_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert,dupl // ok here package microbit import ( @@ -7,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/microbit/temperature_driver.go b/platforms/microbit/temperature_driver.go index 7daf96077..e8eaab283 100644 --- a/platforms/microbit/temperature_driver.go +++ b/platforms/microbit/temperature_driver.go @@ -49,6 +49,7 @@ func (b *TemperatureDriver) SetName(n string) { b.name = n } // adaptor returns BLE adaptor func (b *TemperatureDriver) adaptor() ble.BLEConnector { + //nolint:forcetypeassert // ok here return b.Connection().(ble.BLEConnector) } diff --git a/platforms/microbit/temperature_driver_test.go b/platforms/microbit/temperature_driver_test.go index a24c0f2cb..3d4a81db9 100644 --- a/platforms/microbit/temperature_driver_test.go +++ b/platforms/microbit/temperature_driver_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/mqtt/mqtt_adaptor.go b/platforms/mqtt/mqtt_adaptor.go index 24b412445..3e93efe46 100644 --- a/platforms/mqtt/mqtt_adaptor.go +++ b/platforms/mqtt/mqtt_adaptor.go @@ -6,9 +6,9 @@ import ( "fmt" "os" - "gobot.io/x/gobot/v2" - paho "github.com/eclipse/paho.mqtt.golang" + + "gobot.io/x/gobot/v2" ) // ErrNilClient is returned when a client action can't be taken because the struct has no client @@ -78,7 +78,8 @@ func (a *Adaptor) SetAutoReconnect(val bool) { a.autoReconnect = val } // CleanSession returns the MQTT CleanSession setting func (a *Adaptor) CleanSession() bool { return a.cleanSession } -// SetCleanSession sets the MQTT CleanSession setting. Should be false if reconnect is enabled. Otherwise all subscriptions will be lost +// SetCleanSession sets the MQTT CleanSession setting. Should be false if reconnect is enabled. +// Otherwise all subscriptions will be lost func (a *Adaptor) SetCleanSession(val bool) { a.cleanSession = val } // UseSSL returns the MQTT server SSL preference diff --git a/platforms/mqtt/mqtt_adaptor_test.go b/platforms/mqtt/mqtt_adaptor_test.go index 9a60e4470..04e93bdd2 100644 --- a/platforms/mqtt/mqtt_adaptor_test.go +++ b/platforms/mqtt/mqtt_adaptor_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -74,14 +75,14 @@ func TestMqttAdaptorConnectError(t *testing.T) { a := NewAdaptor("tcp://localhost:1884", "client") err := a.Connect() - assert.Contains(t, err.Error(), "connection refused") + require.ErrorContains(t, err, "connection refused") } func TestMqttAdaptorConnectSSLError(t *testing.T) { a := NewAdaptor("tcp://localhost:1884", "client") a.SetUseSSL(true) err := a.Connect() - assert.Contains(t, err.Error(), "connection refused") + require.ErrorContains(t, err, "connection refused") } func TestMqttAdaptorConnectWithAuthError(t *testing.T) { diff --git a/platforms/mqtt/mqtt_driver.go b/platforms/mqtt/mqtt_driver.go index 68335f951..6747096b3 100644 --- a/platforms/mqtt/mqtt_driver.go +++ b/platforms/mqtt/mqtt_driver.go @@ -47,6 +47,7 @@ func (m *Driver) Connection() gobot.Connection { } func (m *Driver) adaptor() *Adaptor { + //nolint:forcetypeassert // ok here return m.Connection().(*Adaptor) } @@ -68,6 +69,7 @@ func (m *Driver) SetTopic(topic string) { m.topic = topic } // Publish a message to the current device topic func (m *Driver) Publish(data interface{}) bool { + //nolint:forcetypeassert // ok here message := data.([]byte) return m.adaptor().Publish(m.topic, message) } diff --git a/platforms/mqtt/mqtt_driver_test.go b/platforms/mqtt/mqtt_driver_test.go index 8ee028ea5..99aaa5ad6 100644 --- a/platforms/mqtt/mqtt_driver_test.go +++ b/platforms/mqtt/mqtt_driver_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/nanopi/nanopi_adaptor.go b/platforms/nanopi/nanopi_adaptor.go index 46b67c85d..ff298762f 100644 --- a/platforms/nanopi/nanopi_adaptor.go +++ b/platforms/nanopi/nanopi_adaptor.go @@ -5,6 +5,7 @@ import ( "sync" multierror "github.com/hashicorp/go-multierror" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/platforms/adaptors" "gobot.io/x/gobot/v2/system" @@ -167,14 +168,14 @@ func (c *Adaptor) translatePWMPin(id string) (string, int, error) { return path, pinInfo.channel, nil } -func (p pwmPinDefinition) findPWMDir(sys *system.Accesser) (dir string, err error) { +func (p pwmPinDefinition) findPWMDir(sys *system.Accesser) (string, error) { items, _ := sys.Find(p.dir, p.dirRegexp) if len(items) == 0 { return "", fmt.Errorf("No path found for PWM directory pattern, '%s' in path '%s'. See README.md for activation", p.dirRegexp, p.dir) } - dir = items[0] + dir := items[0] info, err := sys.Stat(dir) if err != nil { return "", fmt.Errorf("Error (%v) on access '%s'", err, dir) @@ -183,5 +184,5 @@ func (p pwmPinDefinition) findPWMDir(sys *system.Accesser) (dir string, err erro return "", fmt.Errorf("The item '%s' is not a directory, which is not expected", dir) } - return + return dir, nil } diff --git a/platforms/nanopi/nanopi_adaptor_test.go b/platforms/nanopi/nanopi_adaptor_test.go index 46a36bf08..bfae8fdd0 100644 --- a/platforms/nanopi/nanopi_adaptor_test.go +++ b/platforms/nanopi/nanopi_adaptor_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/gpio" "gobot.io/x/gobot/v2/drivers/i2c" @@ -188,7 +189,7 @@ func TestFinalizeErrorAfterGPIO(t *testing.T) { fs.WithWriteError = true err := a.Finalize() - assert.Contains(t, err.Error(), "write error") + require.ErrorContains(t, err, "write error") } func TestFinalizeErrorAfterPWM(t *testing.T) { @@ -200,7 +201,7 @@ func TestFinalizeErrorAfterPWM(t *testing.T) { fs.WithWriteError = true err := a.Finalize() - assert.Contains(t, err.Error(), "write error") + require.ErrorContains(t, err, "write error") } func TestSpiDefaultValues(t *testing.T) { @@ -232,7 +233,7 @@ func TestI2cFinalizeWithErrors(t *testing.T) { // act err = a.Finalize() // assert - assert.Contains(t, err.Error(), "close error") + require.ErrorContains(t, err, "close error") } func Test_validateSpiBusNumber(t *testing.T) { diff --git a/platforms/nats/nats_adaptor.go b/platforms/nats/nats_adaptor.go index 122cdad9e..1fea0f359 100644 --- a/platforms/nats/nats_adaptor.go +++ b/platforms/nats/nats_adaptor.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/nats-io/nats.go" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/nats/nats_adaptor_test.go b/platforms/nats/nats_adaptor_test.go index 92023cdf0..a2c4bb0c5 100644 --- a/platforms/nats/nats_adaptor_test.go +++ b/platforms/nats/nats_adaptor_test.go @@ -9,6 +9,7 @@ import ( "github.com/nats-io/nats.go" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -92,7 +93,8 @@ func TestNatsAdapterSetsClientCerts(t *testing.T) { } func TestNatsAdapterSetsClientCertsWithUserInfo(t *testing.T) { - a := initTestNatsAdaptorTLS(nats.ClientCert("test_certs/client-cert.pem", "test_certs/client-key.pem"), nats.UserInfo("test", "testwd")) + a := initTestNatsAdaptorTLS(nats.ClientCert("test_certs/client-cert.pem", "test_certs/client-key.pem"), + nats.UserInfo("test", "testwd")) assert.Equal(t, "tls://localhost:4242", a.Host) _ = a.Connect() cert, err := a.client.Opts.TLSCertCB() diff --git a/platforms/nats/nats_driver.go b/platforms/nats/nats_driver.go index 36fab63a1..e4aa7bfd7 100644 --- a/platforms/nats/nats_driver.go +++ b/platforms/nats/nats_driver.go @@ -44,6 +44,7 @@ func (m *Driver) Connection() gobot.Connection { } func (m *Driver) adaptor() *Adaptor { + //nolint:forcetypeassert // ok here return m.Connection().(*Adaptor) } @@ -65,6 +66,7 @@ func (m *Driver) SetTopic(topic string) { m.topic = topic } // Publish a message to the current device topic func (m *Driver) Publish(data interface{}) bool { + //nolint:forcetypeassert // ok here message := data.([]byte) return m.adaptor().Publish(m.topic, message) } diff --git a/platforms/nats/nats_driver_test.go b/platforms/nats/nats_driver_test.go index d35b1d9e4..8b70aeaca 100644 --- a/platforms/nats/nats_driver_test.go +++ b/platforms/nats/nats_driver_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/neurosky/neurosky_adaptor.go b/platforms/neurosky/neurosky_adaptor.go index 874362da9..a0bac066f 100644 --- a/platforms/neurosky/neurosky_adaptor.go +++ b/platforms/neurosky/neurosky_adaptor.go @@ -47,7 +47,6 @@ func (n *Adaptor) Connect() error { } // Finalize returns true if device finalization is successful -func (n *Adaptor) Finalize() (err error) { - err = n.sp.Close() - return +func (n *Adaptor) Finalize() error { + return n.sp.Close() } diff --git a/platforms/neurosky/neurosky_adaptor_test.go b/platforms/neurosky/neurosky_adaptor_test.go index 6f36be7fb..e80ca31e5 100644 --- a/platforms/neurosky/neurosky_adaptor_test.go +++ b/platforms/neurosky/neurosky_adaptor_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/neurosky/neurosky_driver.go b/platforms/neurosky/neurosky_driver.go index 1ebe5198f..893f28bdb 100644 --- a/platforms/neurosky/neurosky_driver.go +++ b/platforms/neurosky/neurosky_driver.go @@ -115,6 +115,7 @@ func (n *Driver) SetName(name string) { n.name = name } // adaptor returns neurosky adaptor func (n *Driver) adaptor() *Adaptor { + //nolint:forcetypeassert // ok here return n.Connection().(*Adaptor) } @@ -124,7 +125,7 @@ func (n *Driver) Start() error { go func() { for { buff := make([]byte, 1024) - _, err := n.adaptor().sp.Read(buff[:]) + _, err := n.adaptor().sp.Read(buff) if err != nil { n.Publish(n.Event("error"), err) } else { diff --git a/platforms/neurosky/neurosky_driver_test.go b/platforms/neurosky/neurosky_driver_test.go index a3c86b048..00dd62a78 100644 --- a/platforms/neurosky/neurosky_driver_test.go +++ b/platforms/neurosky/neurosky_driver_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert // ok here package neurosky import ( @@ -10,6 +11,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/opencv/camera_driver.go b/platforms/opencv/camera_driver.go index e83aa5f8c..9a4e8136c 100644 --- a/platforms/opencv/camera_driver.go +++ b/platforms/opencv/camera_driver.go @@ -21,7 +21,7 @@ type CameraDriver struct { name string camera capture Source interface{} - start func(*CameraDriver) (err error) + start func(*CameraDriver) error gobot.Eventer } @@ -32,7 +32,7 @@ func NewCameraDriver(source interface{}) *CameraDriver { name: "Camera", Eventer: gobot.NewEventer(), Source: source, - start: func(c *CameraDriver) (err error) { + start: func(c *CameraDriver) error { switch v := c.Source.(type) { case string: c.camera, _ = gocv.VideoCaptureFile(v) @@ -60,7 +60,7 @@ func (c *CameraDriver) SetName(n string) { c.name = n } func (c *CameraDriver) Connection() gobot.Connection { return nil } // Start initializes camera by grabbing frames -func (c *CameraDriver) Start() (err error) { +func (c *CameraDriver) Start() error { if err := c.start(c); err != nil { return err } @@ -76,4 +76,4 @@ func (c *CameraDriver) Start() (err error) { } // Halt stops camera driver -func (c *CameraDriver) Halt() (err error) { return } +func (c *CameraDriver) Halt() error { return nil } diff --git a/platforms/opencv/camera_driver_test.go b/platforms/opencv/camera_driver_test.go index 5b4adda1a..9a475bcc9 100644 --- a/platforms/opencv/camera_driver_test.go +++ b/platforms/opencv/camera_driver_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -14,7 +15,7 @@ var _ gobot.Driver = (*CameraDriver)(nil) func initTestCameraDriver() *CameraDriver { d := NewCameraDriver("") - d.start = func(c *CameraDriver) (err error) { + d.start = func(c *CameraDriver) error { d.camera = &testCapture{} return nil } diff --git a/platforms/opencv/utils_test.go b/platforms/opencv/utils_test.go index 924dd53d7..775f2df60 100644 --- a/platforms/opencv/utils_test.go +++ b/platforms/opencv/utils_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "gocv.io/x/gocv" ) diff --git a/platforms/opencv/window_driver.go b/platforms/opencv/window_driver.go index 7d6eb2fc5..a1130e521 100644 --- a/platforms/opencv/window_driver.go +++ b/platforms/opencv/window_driver.go @@ -37,13 +37,13 @@ func (w *WindowDriver) SetName(n string) { w.name = n } func (w *WindowDriver) Connection() gobot.Connection { return nil } // Start starts window thread and driver -func (w *WindowDriver) Start() (err error) { +func (w *WindowDriver) Start() error { w.start(w) return } // Halt returns true if camera is halted successfully -func (w *WindowDriver) Halt() (err error) { return } +func (w *WindowDriver) Halt() error { return } // ShowImage displays image in window func (w *WindowDriver) ShowImage(img gocv.Mat) { diff --git a/platforms/opencv/window_driver_test.go b/platforms/opencv/window_driver_test.go index ae7ba808e..36bebcf90 100644 --- a/platforms/opencv/window_driver_test.go +++ b/platforms/opencv/window_driver_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gocv.io/x/gocv" ) diff --git a/platforms/parrot/ardrone/ardrone_adaptor.go b/platforms/parrot/ardrone/ardrone_adaptor.go index 336de7ff4..a1b727b1b 100644 --- a/platforms/parrot/ardrone/ardrone_adaptor.go +++ b/platforms/parrot/ardrone/ardrone_adaptor.go @@ -2,6 +2,7 @@ package ardrone import ( client "github.com/hybridgroup/go-ardrone/client" + "gobot.io/x/gobot/v2" ) @@ -54,14 +55,14 @@ func (a *Adaptor) Name() string { return a.name } func (a *Adaptor) SetName(n string) { a.name = n } // Connect establishes a connection to the ardrone -func (a *Adaptor) Connect() (err error) { +func (a *Adaptor) Connect() error { d, err := a.connect(a) if err != nil { return err } a.drone = d - return + return nil } // Finalize terminates the connection to the ardrone -func (a *Adaptor) Finalize() (err error) { return } +func (a *Adaptor) Finalize() error { return nil } diff --git a/platforms/parrot/ardrone/ardrone_adaptor_test.go b/platforms/parrot/ardrone/ardrone_adaptor_test.go index c8eb5c59c..aa67acb08 100644 --- a/platforms/parrot/ardrone/ardrone_adaptor_test.go +++ b/platforms/parrot/ardrone/ardrone_adaptor_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/parrot/ardrone/ardrone_driver.go b/platforms/parrot/ardrone/ardrone_driver.go index f5e279337..df7c1a5bb 100644 --- a/platforms/parrot/ardrone/ardrone_driver.go +++ b/platforms/parrot/ardrone/ardrone_driver.go @@ -42,17 +42,18 @@ func (a *Driver) Connection() gobot.Connection { return a.connection } // adaptor returns ardrone adaptor func (a *Driver) adaptor() *Adaptor { + //nolint:forcetypeassert // ok here return a.Connection().(*Adaptor) } // Start starts the Driver -func (a *Driver) Start() (err error) { - return +func (a *Driver) Start() error { + return nil } // Halt halts the Driver -func (a *Driver) Halt() (err error) { - return +func (a *Driver) Halt() error { + return nil } // TakeOff makes the drone start flying, and publishes `flying` event diff --git a/platforms/parrot/ardrone/ardrone_driver_test.go b/platforms/parrot/ardrone/ardrone_driver_test.go index 9664cd71f..2cdaf57e8 100644 --- a/platforms/parrot/ardrone/ardrone_driver_test.go +++ b/platforms/parrot/ardrone/ardrone_driver_test.go @@ -5,6 +5,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/parrot/bebop/bebop_adaptor_test.go b/platforms/parrot/bebop/bebop_adaptor_test.go index c5c2dd039..966341709 100644 --- a/platforms/parrot/bebop/bebop_adaptor_test.go +++ b/platforms/parrot/bebop/bebop_adaptor_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -14,7 +15,7 @@ var _ gobot.Adaptor = (*Adaptor)(nil) func initTestBebopAdaptor() *Adaptor { a := NewAdaptor() - a.connect = func(b *Adaptor) (err error) { + a.connect = func(b *Adaptor) error { b.drone = &testDrone{} return nil } diff --git a/platforms/parrot/bebop/bebop_driver.go b/platforms/parrot/bebop/bebop_driver.go index b0d1c0f4f..8abed2ef4 100644 --- a/platforms/parrot/bebop/bebop_driver.go +++ b/platforms/parrot/bebop/bebop_driver.go @@ -38,17 +38,18 @@ func (a *Driver) Connection() gobot.Connection { return a.connection } // adaptor returns ardrone adaptor func (a *Driver) adaptor() *Adaptor { + //nolint:forcetypeassert // ok here return a.Connection().(*Adaptor) } // Start starts the Bebop Driver -func (a *Driver) Start() (err error) { - return +func (a *Driver) Start() error { + return nil } // Halt halts the Bebop Driver -func (a *Driver) Halt() (err error) { - return +func (a *Driver) Halt() error { + return nil } // TakeOff makes the drone start flying @@ -131,7 +132,8 @@ func (a *Driver) StopRecording() error { return a.adaptor().drone.StopRecording() } -// HullProtection tells the drone if the hull/prop protectors are attached. This is needed to adjust flight characteristics of the Bebop. +// HullProtection tells the drone if the hull/prop protectors are attached. This is needed to adjust +// flight characteristics of the Bebop. func (a *Driver) HullProtection(protect bool) error { return a.adaptor().drone.HullProtection(protect) } diff --git a/platforms/parrot/bebop/bebop_driver_test.go b/platforms/parrot/bebop/bebop_driver_test.go index 6685eb650..8e98891f8 100644 --- a/platforms/parrot/bebop/bebop_driver_test.go +++ b/platforms/parrot/bebop/bebop_driver_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/parrot/bebop/client/client.go b/platforms/parrot/bebop/client/client.go index 9d54c183b..08451c1b4 100644 --- a/platforms/parrot/bebop/client/client.go +++ b/platforms/parrot/bebop/client/client.go @@ -108,7 +108,7 @@ func NewNetworkFrame(buf []byte) NetworkFrame { } func networkFrameGenerator() func(*bytes.Buffer, byte, byte) *bytes.Buffer { - //func networkFrameGenerator() func(*bytes.Buffer, byte, byte) NetworkFrame { + // func networkFrameGenerator() func(*bytes.Buffer, byte, byte) NetworkFrame { // // ARNETWORKAL_Frame_t // diff --git a/platforms/parrot/minidrone/helpers_test.go b/platforms/parrot/minidrone/helpers_test.go index 1f860b4e3..48106b64d 100644 --- a/platforms/parrot/minidrone/helpers_test.go +++ b/platforms/parrot/minidrone/helpers_test.go @@ -17,30 +17,30 @@ type bleTestClientAdaptor struct { testWriteCharacteristic func(string, []byte) error } -func (t *bleTestClientAdaptor) Connect() (err error) { return } -func (t *bleTestClientAdaptor) Reconnect() (err error) { return } -func (t *bleTestClientAdaptor) Disconnect() (err error) { return } -func (t *bleTestClientAdaptor) Finalize() (err error) { return } +func (t *bleTestClientAdaptor) Connect() error { return nil } +func (t *bleTestClientAdaptor) Reconnect() error { return nil } +func (t *bleTestClientAdaptor) Disconnect() error { return nil } +func (t *bleTestClientAdaptor) Finalize() error { return nil } func (t *bleTestClientAdaptor) Name() string { return t.name } func (t *bleTestClientAdaptor) SetName(n string) { t.name = n } func (t *bleTestClientAdaptor) Address() string { return t.address } func (t *bleTestClientAdaptor) WithoutResponses(use bool) { t.withoutResponses = use } -func (t *bleTestClientAdaptor) ReadCharacteristic(cUUID string) (data []byte, err error) { +func (t *bleTestClientAdaptor) ReadCharacteristic(cUUID string) ([]byte, error) { t.mtx.Lock() defer t.mtx.Unlock() return t.testReadCharacteristic(cUUID) } -func (t *bleTestClientAdaptor) WriteCharacteristic(cUUID string, data []byte) (err error) { +func (t *bleTestClientAdaptor) WriteCharacteristic(cUUID string, data []byte) error { t.mtx.Lock() defer t.mtx.Unlock() return t.testWriteCharacteristic(cUUID, data) } -func (t *bleTestClientAdaptor) Subscribe(cUUID string, f func([]byte, error)) (err error) { +func (t *bleTestClientAdaptor) Subscribe(cUUID string, f func([]byte, error)) error { // TODO: implement this... - return + return nil } func (t *bleTestClientAdaptor) TestReadCharacteristic(f func(cUUID string) (data []byte, err error)) { @@ -49,7 +49,7 @@ func (t *bleTestClientAdaptor) TestReadCharacteristic(f func(cUUID string) (data t.testReadCharacteristic = f } -func (t *bleTestClientAdaptor) TestWriteCharacteristic(f func(cUUID string, data []byte) (err error)) { +func (t *bleTestClientAdaptor) TestWriteCharacteristic(f func(cUUID string, data []byte) error) { t.mtx.Lock() defer t.mtx.Unlock() t.testWriteCharacteristic = f @@ -58,11 +58,11 @@ func (t *bleTestClientAdaptor) TestWriteCharacteristic(f func(cUUID string, data func NewBleTestAdaptor() *bleTestClientAdaptor { return &bleTestClientAdaptor{ address: "01:02:03:04:05:06", - testReadCharacteristic: func(cUUID string) (data []byte, e error) { - return + testReadCharacteristic: func(cUUID string) ([]byte, error) { + return nil, nil }, - testWriteCharacteristic: func(cUUID string, data []byte) (e error) { - return + testWriteCharacteristic: func(cUUID string, data []byte) error { + return nil }, } } diff --git a/platforms/parrot/minidrone/minidrone_driver.go b/platforms/parrot/minidrone/minidrone_driver.go index 926ea0bdb..904fe842d 100644 --- a/platforms/parrot/minidrone/minidrone_driver.go +++ b/platforms/parrot/minidrone/minidrone_driver.go @@ -147,6 +147,7 @@ func (b *Driver) SetName(n string) { b.name = n } // adaptor returns BLE adaptor func (b *Driver) adaptor() ble.BLEConnector { + //nolint:forcetypeassert // ok here return b.Connection().(ble.BLEConnector) } @@ -194,7 +195,9 @@ func (b *Driver) Init() error { // GenerateAllStates sets up all the default states aka settings on the drone func (b *Driver) GenerateAllStates() error { b.stepsfa0b++ - buf := []byte{0x04, byte(b.stepsfa0b), 0x00, 0x04, 0x01, 0x00, 0x32, 0x30, 0x31, 0x34, 0x2D, 0x31, 0x30, 0x2D, 0x32, 0x38, 0x00} + buf := []byte{ + 0x04, byte(b.stepsfa0b), 0x00, 0x04, 0x01, 0x00, 0x32, 0x30, 0x31, 0x34, 0x2D, 0x31, 0x30, 0x2D, 0x32, 0x38, 0x00, + } return b.adaptor().WriteCharacteristic(commandCharacteristic, buf) } diff --git a/platforms/parrot/minidrone/minidrone_driver_test.go b/platforms/parrot/minidrone/minidrone_driver_test.go index ec65a3ff5..cd6bb4e06 100644 --- a/platforms/parrot/minidrone/minidrone_driver_test.go +++ b/platforms/parrot/minidrone/minidrone_driver_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/particle/adaptor.go b/platforms/particle/adaptor.go index 365621a2c..406586e88 100644 --- a/platforms/particle/adaptor.go +++ b/platforms/particle/adaptor.go @@ -10,6 +10,7 @@ import ( "strconv" "github.com/donovanhide/eventsource" + "gobot.io/x/gobot/v2" ) @@ -74,6 +75,7 @@ func (s *Adaptor) AnalogRead(pin string) (int, error) { resp, err := s.request("POST", url, params) if err == nil { + //nolint:forcetypeassert // ok here return int(resp["return_value"].(float64)), nil } @@ -119,6 +121,7 @@ func (s *Adaptor) DigitalRead(pin string) (int, error) { return -1, err } + //nolint:forcetypeassert // ok here return int(resp["return_value"].(float64)), nil } @@ -147,7 +150,7 @@ func (s *Adaptor) ServoWrite(pin string, angle byte) error { // * name - Event name to subscribe for, leave blank to subscribe to all events. // // A new event is emitted as a particle.Event struct -func (s *Adaptor) EventStream(source string, name string) (event *gobot.Event, err error) { +func (s *Adaptor) EventStream(source string, name string) (*gobot.Event, error) { var url string switch source { @@ -158,13 +161,12 @@ func (s *Adaptor) EventStream(source string, name string) (event *gobot.Event, e case "device": url = fmt.Sprintf("%s/events/%s?access_token=%s", s.deviceURL(), name, s.AccessToken) default: - err = errors.New("source param should be: all, devices or device") - return + return nil, errors.New("source param should be: all, devices or device") } events, _, err := eventSource(url) if err != nil { - return + return nil, err } go func() { @@ -175,17 +177,19 @@ func (s *Adaptor) EventStream(source string, name string) (event *gobot.Event, e } } }() - return + + return nil, nil //nolint:nilnil // seems ok here } // Variable returns a core variable value as a string -func (s *Adaptor) Variable(name string) (result string, err error) { +func (s *Adaptor) Variable(name string) (string, 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 + return "", err } + var result string switch val := resp["result"].(type) { case bool: result = strconv.FormatBool(val) @@ -195,7 +199,7 @@ func (s *Adaptor) Variable(name string) (result string, err error) { result = val } - return + return result, nil } // Function executes a core function and @@ -214,6 +218,7 @@ func (s *Adaptor) Function(name string, args string) (int, error) { return -1, err } + //nolint:forcetypeassert // ok here return int(resp["return_value"].(float64)), nil } @@ -224,7 +229,7 @@ func (s *Adaptor) setAPIServer(server string) { // deviceURL constructs device url to make requests from Particle cloud api func (s *Adaptor) deviceURL() string { - if len(s.APIServer) <= 0 { + if len(s.APIServer) == 0 { s.setAPIServer("https://api.particle.io") } return fmt.Sprintf("%v/v1/devices/%v", s.APIServer, s.DeviceID) @@ -240,9 +245,11 @@ func (s *Adaptor) pinLevel(level byte) string { // request makes request to Particle cloud server, return err != nil if there is // any issue with the request. -func (s *Adaptor) request(method string, url string, params url.Values) (m map[string]interface{}, err error) { +// +//nolint:bodyclose,noctx // not changed yet +func (s *Adaptor) request(method string, url string, params url.Values) (map[string]interface{}, error) { var resp *http.Response - + var err error if method == "POST" { resp, err = http.PostForm(url, params) //nolint:gosec // accepted, because local function and no exposed routing } else if method == "GET" { @@ -250,25 +257,29 @@ func (s *Adaptor) request(method string, url string, params url.Values) (m map[s } if err != nil { - return + return nil, err } buf, err := io.ReadAll(resp.Body) if err != nil { - return + return nil, err } + var m map[string]interface{} if err := json.Unmarshal(buf, &m); err != nil { return m, err } if resp.Status != "200 OK" { - err = fmt.Errorf("%v: error communicating to the Particle cloud", resp.Status) - } else if _, ok := m["error"]; ok { - err = errors.New(m["error"].(string)) + return m, fmt.Errorf("%v: error communicating to the Particle cloud", resp.Status) + } + + if _, ok := m["error"]; ok { + //nolint:forcetypeassert // ok here + return m, errors.New(m["error"].(string)) } - return + return m, nil } func (s *Adaptor) servoPinOpen(pin string) error { diff --git a/platforms/particle/adaptor_test.go b/platforms/particle/adaptor_test.go index 20b5c632d..ee79d51ec 100644 --- a/platforms/particle/adaptor_test.go +++ b/platforms/particle/adaptor_test.go @@ -11,6 +11,7 @@ import ( "github.com/donovanhide/eventsource" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -20,7 +21,9 @@ func createTestServer(handler func(w http.ResponseWriter, r *http.Request)) *htt return httptest.NewServer(http.HandlerFunc(handler)) } -func getDummyResponseForPath(path string, dummyResponse string, t *testing.T) *httptest.Server { +func getDummyResponseForPath(t *testing.T, path string, dummyResponse string) *httptest.Server { + t.Helper() + dummyData := []byte(dummyResponse) return createTestServer(func(w http.ResponseWriter, r *http.Request) { @@ -32,7 +35,14 @@ func getDummyResponseForPath(path string, dummyResponse string, t *testing.T) *h }) } -func getDummyResponseForPathWithParams(path string, params []string, dummyResponse string, t *testing.T) *httptest.Server { +func getDummyResponseForPathWithParams( + t *testing.T, + path string, + params []string, + dummyResponse string, +) *httptest.Server { + t.Helper() + dummyData := []byte(dummyResponse) return createTestServer(func(w http.ResponseWriter, r *http.Request) { @@ -104,7 +114,7 @@ func TestAdaptorAnalogRead(t *testing.T) { params := []string{"A1"} a := initTestAdaptor() - testServer := getDummyResponseForPathWithParams("/"+a.DeviceID+"/analogread", params, response, t) + testServer := getDummyResponseForPathWithParams(t, "/"+a.DeviceID+"/analogread", params, response) a.setAPIServer(testServer.URL) defer testServer.Close() @@ -131,7 +141,7 @@ func TestAdaptorPwmWrite(t *testing.T) { params := []string{"A1,1"} a := initTestAdaptor() - testServer := getDummyResponseForPathWithParams("/"+a.DeviceID+"/analogwrite", params, response, t) + testServer := getDummyResponseForPathWithParams(t, "/"+a.DeviceID+"/analogwrite", params, response) defer testServer.Close() a.setAPIServer(testServer.URL) @@ -143,7 +153,7 @@ func TestAdaptorAnalogWrite(t *testing.T) { params := []string{"A1,1"} a := initTestAdaptor() - testServer := getDummyResponseForPathWithParams("/"+a.DeviceID+"/analogwrite", params, response, t) + testServer := getDummyResponseForPathWithParams(t, "/"+a.DeviceID+"/analogwrite", params, response) defer testServer.Close() a.setAPIServer(testServer.URL) @@ -156,7 +166,7 @@ func TestAdaptorDigitalWrite(t *testing.T) { params := []string{"D7,HIGH"} a := initTestAdaptor() - testServer := getDummyResponseForPathWithParams("/"+a.DeviceID+"/digitalwrite", params, response, t) + testServer := getDummyResponseForPathWithParams(t, "/"+a.DeviceID+"/digitalwrite", params, response) a.setAPIServer(testServer.URL) _ = a.DigitalWrite("D7", 1) @@ -165,7 +175,7 @@ func TestAdaptorDigitalWrite(t *testing.T) { // When LOW params = []string{"D7,LOW"} - testServer = getDummyResponseForPathWithParams("/"+a.DeviceID+"/digitalwrite", params, response, t) + testServer = getDummyResponseForPathWithParams(t, "/"+a.DeviceID+"/digitalwrite", params, response) defer testServer.Close() a.setAPIServer(testServer.URL) @@ -177,7 +187,7 @@ func TestAdaptorServoOpen(t *testing.T) { params := []string{"1"} a := initTestAdaptor() - testServer := getDummyResponseForPathWithParams("/"+a.DeviceID+"/servoOpen", params, response, t) + testServer := getDummyResponseForPathWithParams(t, "/"+a.DeviceID+"/servoOpen", params, response) defer testServer.Close() a.setAPIServer(testServer.URL) @@ -189,7 +199,7 @@ func TestAdaptorServoWrite(t *testing.T) { params := []string{"1,128"} a := initTestAdaptorWithServo() - testServer := getDummyResponseForPathWithParams("/"+a.DeviceID+"/servoSet", params, response, t) + testServer := getDummyResponseForPathWithParams(t, "/"+a.DeviceID+"/servoSet", params, response) defer testServer.Close() a.setAPIServer(testServer.URL) @@ -202,7 +212,7 @@ func TestAdaptorDigitalRead(t *testing.T) { params := []string{"D7"} a := initTestAdaptor() - testServer := getDummyResponseForPathWithParams("/"+a.DeviceID+"/digitalread", params, response, t) + testServer := getDummyResponseForPathWithParams(t, "/"+a.DeviceID+"/digitalread", params, response) a.setAPIServer(testServer.URL) @@ -213,7 +223,7 @@ func TestAdaptorDigitalRead(t *testing.T) { // When LOW response = `{"return_value": 0}` - testServer = getDummyResponseForPathWithParams("/"+a.DeviceID+"/digitalread", params, response, t) + testServer = getDummyResponseForPathWithParams(t, "/"+a.DeviceID+"/digitalread", params, response) a.setAPIServer(testServer.URL) defer testServer.Close() @@ -240,7 +250,7 @@ func TestAdaptorFunction(t *testing.T) { response := `{"return_value": 1}` a := initTestAdaptor() - testServer := getDummyResponseForPath("/"+a.DeviceID+"/hello", response, t) + testServer := getDummyResponseForPath(t, "/"+a.DeviceID+"/hello", response) a.setAPIServer(testServer.URL) @@ -250,7 +260,7 @@ func TestAdaptorFunction(t *testing.T) { // When not existent response = `{"ok": false, "error": "timeout"}` - testServer = getDummyResponseForPath("/"+a.DeviceID+"/hello", response, t) + testServer = getDummyResponseForPath(t, "/"+a.DeviceID+"/hello", response) a.setAPIServer(testServer.URL) @@ -265,7 +275,7 @@ func TestAdaptorVariable(t *testing.T) { response := `{"result": "1"}` a := initTestAdaptor() - testServer := getDummyResponseForPath("/"+a.DeviceID+"/variable_name", response, t) + testServer := getDummyResponseForPath(t, "/"+a.DeviceID+"/variable_name", response) a.setAPIServer(testServer.URL) @@ -275,7 +285,7 @@ func TestAdaptorVariable(t *testing.T) { // When float response = `{"result": 1.1}` - testServer = getDummyResponseForPath("/"+a.DeviceID+"/variable_name", response, t) + testServer = getDummyResponseForPath(t, "/"+a.DeviceID+"/variable_name", response) a.setAPIServer(testServer.URL) @@ -285,7 +295,7 @@ func TestAdaptorVariable(t *testing.T) { // When int response = `{"result": 1}` - testServer = getDummyResponseForPath("/"+a.DeviceID+"/variable_name", response, t) + testServer = getDummyResponseForPath(t, "/"+a.DeviceID+"/variable_name", response) a.setAPIServer(testServer.URL) @@ -295,7 +305,7 @@ func TestAdaptorVariable(t *testing.T) { // When bool response = `{"result": true}` - testServer = getDummyResponseForPath("/"+a.DeviceID+"/variable_name", response, t) + testServer = getDummyResponseForPath(t, "/"+a.DeviceID+"/variable_name", response) a.setAPIServer(testServer.URL) @@ -305,7 +315,7 @@ func TestAdaptorVariable(t *testing.T) { // When not existent response = `{"ok": false, "error": "Variable not found"}` - testServer = getDummyResponseForPath("/"+a.DeviceID+"/not_existent", response, t) + testServer = getDummyResponseForPath(t, "/"+a.DeviceID+"/not_existent", response) a.setAPIServer(testServer.URL) diff --git a/platforms/pebble/doc.go b/platforms/pebble/doc.go index 7c6654555..686eb837a 100644 --- a/platforms/pebble/doc.go +++ b/platforms/pebble/doc.go @@ -10,7 +10,8 @@ installed on Pebble watch. Then install running: Example: -Before running the example, make sure configuration settings match with your program. In the example, api host is your computer IP, robot name is 'pebble' and robot api port is 8080 +Before running the example, make sure configuration settings match with your program. In the example, api host is +your computer IP, robot name is 'pebble' and robot api port is 8080 package main diff --git a/platforms/pebble/pebble_adaptor.go b/platforms/pebble/pebble_adaptor.go index 2555c91df..8dbac9073 100644 --- a/platforms/pebble/pebble_adaptor.go +++ b/platforms/pebble/pebble_adaptor.go @@ -15,11 +15,11 @@ func (a *Adaptor) Name() string { return a.name } func (a *Adaptor) SetName(n string) { a.name = n } // Connect returns true if connection to pebble is established successfully -func (a *Adaptor) Connect() (err error) { - return +func (a *Adaptor) Connect() error { + return nil } // Finalize returns true if connection to pebble is finalized successfully -func (a *Adaptor) Finalize() (err error) { - return +func (a *Adaptor) Finalize() error { + return nil } diff --git a/platforms/pebble/pebble_adaptor_test.go b/platforms/pebble/pebble_adaptor_test.go index 03e3eb64f..995fb27f2 100644 --- a/platforms/pebble/pebble_adaptor_test.go +++ b/platforms/pebble/pebble_adaptor_test.go @@ -5,6 +5,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/pebble/pebble_driver.go b/platforms/pebble/pebble_driver.go index 406a95119..345b9beaa 100644 --- a/platforms/pebble/pebble_driver.go +++ b/platforms/pebble/pebble_driver.go @@ -37,11 +37,12 @@ func NewDriver(adaptor *Adaptor) *Driver { p.AddEvent("accel") p.AddEvent("tap") + //nolint:forcetypeassert // ok here p.AddCommand("publish_event", func(params map[string]interface{}) interface{} { p.PublishEvent(params["name"].(string), params["data"].(string)) return nil }) - + //nolint:forcetypeassert // ok here p.AddCommand("send_notification", func(params map[string]interface{}) interface{} { p.SendNotification(params["message"].(string)) return nil @@ -58,10 +59,10 @@ func (d *Driver) SetName(n string) { d.name = n } func (d *Driver) Connection() gobot.Connection { return d.connection } // Start returns true if driver is initialized correctly -func (d *Driver) Start() (err error) { return } +func (d *Driver) Start() error { return nil } // Halt returns true if driver is halted successfully -func (d *Driver) Halt() (err error) { return } +func (d *Driver) Halt() error { return nil } // PublishEvent publishes event with specified name and data in gobot func (d *Driver) PublishEvent(name string, data string) { diff --git a/platforms/pebble/pebble_driver_test.go b/platforms/pebble/pebble_driver_test.go index 2087f1477..1c6d1ae4a 100644 --- a/platforms/pebble/pebble_driver_test.go +++ b/platforms/pebble/pebble_driver_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/raspi/pwm_pin.go b/platforms/raspi/pwm_pin.go index 05f49a952..70aa59452 100644 --- a/platforms/raspi/pwm_pin.go +++ b/platforms/raspi/pwm_pin.go @@ -54,7 +54,7 @@ func (p *PWMPin) Polarity() (bool, error) { } // SetPolarity does not do anything when using PiBlaster -func (p *PWMPin) SetPolarity(bool) (err error) { +func (p *PWMPin) SetPolarity(bool) error { return nil } @@ -106,7 +106,7 @@ func (p *PWMPin) SetDutyCycle(duty uint32) error { return nil } -func (p *PWMPin) writeValue(data string) (err error) { +func (p *PWMPin) writeValue(data string) error { fi, err := p.sys.OpenFile(p.path, os.O_WRONLY|os.O_APPEND, 0o644) defer fi.Close() //nolint:staticcheck // for historical reasons @@ -115,5 +115,5 @@ func (p *PWMPin) writeValue(data string) (err error) { } _, err = fi.WriteString(data) - return + return err } diff --git a/platforms/raspi/pwm_pin_test.go b/platforms/raspi/pwm_pin_test.go index c2bfa6155..f25cd0c08 100644 --- a/platforms/raspi/pwm_pin_test.go +++ b/platforms/raspi/pwm_pin_test.go @@ -5,6 +5,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/system" ) diff --git a/platforms/raspi/raspi_adaptor.go b/platforms/raspi/raspi_adaptor.go index 2d915d550..f87608c36 100644 --- a/platforms/raspi/raspi_adaptor.go +++ b/platforms/raspi/raspi_adaptor.go @@ -8,6 +8,7 @@ import ( "sync" multierror "github.com/hashicorp/go-multierror" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/platforms/adaptors" "gobot.io/x/gobot/v2/system" @@ -139,7 +140,7 @@ func (c *Adaptor) PWMPin(id string) (gobot.PWMPinner, error) { } // PwmWrite writes a PWM signal to the specified pin -func (c *Adaptor) PwmWrite(pin string, val byte) (err error) { +func (c *Adaptor) PwmWrite(pin string, val byte) error { c.mutex.Lock() defer c.mutex.Unlock() @@ -153,7 +154,7 @@ func (c *Adaptor) PwmWrite(pin string, val byte) (err error) { } // ServoWrite writes a servo signal to the specified pin -func (c *Adaptor) ServoWrite(pin string, angle byte) (err error) { +func (c *Adaptor) ServoWrite(pin string, angle byte) error { c.mutex.Lock() defer c.mutex.Unlock() @@ -184,14 +185,14 @@ func (c *Adaptor) validateI2cBusNumber(busNr int) error { } func (c *Adaptor) getPinTranslatorFunction() func(string) (string, int, error) { - return func(pin string) (chip string, line int, err error) { + return func(pin string) (string, int, error) { + var line int if val, ok := pins[pin][c.readRevision()]; ok { line = val } else if val, ok := pins[pin]["*"]; ok { line = val } else { - err = errors.New("Not a valid pin") - return + return "", 0, errors.New("Not a valid pin") } // TODO: Pi1 model B has only this single "gpiochip0", a change of the translator is needed, // to support different chips with different revisions @@ -210,11 +211,12 @@ func (c *Adaptor) readRevision() string { if strings.Contains(v, "Revision") { s := strings.Split(v, " ") version, _ := strconv.ParseInt("0x"+s[len(s)-1], 0, 64) - if version <= 3 { + switch { + case version <= 3: c.revision = "1" - } else if version <= 15 { + case version <= 15: c.revision = "2" - } else { + default: c.revision = "3" } } diff --git a/platforms/raspi/raspi_adaptor_test.go b/platforms/raspi/raspi_adaptor_test.go index cd78959c8..4fd330ecb 100644 --- a/platforms/raspi/raspi_adaptor_test.go +++ b/platforms/raspi/raspi_adaptor_test.go @@ -10,6 +10,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/gpio" "gobot.io/x/gobot/v2/drivers/i2c" @@ -272,7 +273,7 @@ func TestI2cFinalizeWithErrors(t *testing.T) { // act err = a.Finalize() // assert - assert.Contains(t, err.Error(), "close error") + require.ErrorContains(t, err, "close error") } func Test_validateSpiBusNumber(t *testing.T) { diff --git a/platforms/rockpi/rockpi_adaptor.go b/platforms/rockpi/rockpi_adaptor.go index 321b7a688..13418f86c 100644 --- a/platforms/rockpi/rockpi_adaptor.go +++ b/platforms/rockpi/rockpi_adaptor.go @@ -6,6 +6,7 @@ import ( "sync" multierror "github.com/hashicorp/go-multierror" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/platforms/adaptors" "gobot.io/x/gobot/v2/system" @@ -40,7 +41,7 @@ type Adaptor struct { // // Optional parameters: // -// adaptors.WithGpiodAccess(): use character device gpiod driver instead of the default sysfs (does NOT work on RockPi4C+!) +// adaptors.WithGpiodAccess(): use character device gpiod driver instead of the default sysfs (NOT work on RockPi4C+!) // adaptors.WithSpiGpioAccess(sclk, nss, mosi, miso): use GPIO's instead of /dev/spidev#.# // adaptors.WithGpiosActiveLow(pin's): invert the pin behavior func NewAdaptor(opts ...func(adaptors.Optioner)) *Adaptor { @@ -124,14 +125,14 @@ func (c *Adaptor) validateI2cBusNumber(busNr int) error { } func (c *Adaptor) getPinTranslatorFunction() func(string) (string, int, error) { - return func(pin string) (chip string, line int, err error) { + return func(pin string) (string, int, error) { + var line int if val, ok := pins[pin][c.readRevision()]; ok { line = val } else if val, ok := pins[pin]["*"]; ok { line = val } else { - err = errors.New("Not a valid pin") - return + return "", 0, errors.New("Not a valid pin") } return "", line, nil } diff --git a/platforms/rockpi/rockpi_adaptor_test.go b/platforms/rockpi/rockpi_adaptor_test.go index 9d1d590e8..617cee981 100644 --- a/platforms/rockpi/rockpi_adaptor_test.go +++ b/platforms/rockpi/rockpi_adaptor_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "gobot.io/x/gobot/v2/system" ) diff --git a/platforms/sphero/bb8/bb8_driver_test.go b/platforms/sphero/bb8/bb8_driver_test.go index 05c3f425d..b0ec1c1b9 100644 --- a/platforms/sphero/bb8/bb8_driver_test.go +++ b/platforms/sphero/bb8/bb8_driver_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/sphero/bb8/helpers_test.go b/platforms/sphero/bb8/helpers_test.go index da6f58245..9738f6987 100644 --- a/platforms/sphero/bb8/helpers_test.go +++ b/platforms/sphero/bb8/helpers_test.go @@ -18,30 +18,30 @@ type bleTestClientAdaptor struct { testWriteCharacteristic func(string, []byte) error } -func (t *bleTestClientAdaptor) Connect() (err error) { return } -func (t *bleTestClientAdaptor) Reconnect() (err error) { return } -func (t *bleTestClientAdaptor) Disconnect() (err error) { return } -func (t *bleTestClientAdaptor) Finalize() (err error) { return } +func (t *bleTestClientAdaptor) Connect() error { return nil } +func (t *bleTestClientAdaptor) Reconnect() error { return nil } +func (t *bleTestClientAdaptor) Disconnect() error { return nil } +func (t *bleTestClientAdaptor) Finalize() error { return nil } func (t *bleTestClientAdaptor) Name() string { return t.name } func (t *bleTestClientAdaptor) SetName(n string) { t.name = n } func (t *bleTestClientAdaptor) Address() string { return t.address } func (t *bleTestClientAdaptor) WithoutResponses(use bool) { t.withoutResponses = use } -func (t *bleTestClientAdaptor) ReadCharacteristic(cUUID string) (data []byte, err error) { +func (t *bleTestClientAdaptor) ReadCharacteristic(cUUID string) ([]byte, error) { t.mtx.Lock() defer t.mtx.Unlock() return t.testReadCharacteristic(cUUID) } -func (t *bleTestClientAdaptor) WriteCharacteristic(cUUID string, data []byte) (err error) { +func (t *bleTestClientAdaptor) WriteCharacteristic(cUUID string, data []byte) error { t.mtx.Lock() defer t.mtx.Unlock() return t.testWriteCharacteristic(cUUID, data) } -func (t *bleTestClientAdaptor) Subscribe(cUUID string, f func([]byte, error)) (err error) { +func (t *bleTestClientAdaptor) Subscribe(cUUID string, f func([]byte, error)) error { // TODO: implement this... - return + return nil } func (t *bleTestClientAdaptor) TestReadCharacteristic(f func(cUUID string) (data []byte, err error)) { @@ -50,7 +50,7 @@ func (t *bleTestClientAdaptor) TestReadCharacteristic(f func(cUUID string) (data t.testReadCharacteristic = f } -func (t *bleTestClientAdaptor) TestWriteCharacteristic(f func(cUUID string, data []byte) (err error)) { +func (t *bleTestClientAdaptor) TestWriteCharacteristic(f func(cUUID string, data []byte) error) { t.mtx.Lock() defer t.mtx.Unlock() t.testWriteCharacteristic = f @@ -59,11 +59,11 @@ func (t *bleTestClientAdaptor) TestWriteCharacteristic(f func(cUUID string, data func NewBleTestAdaptor() *bleTestClientAdaptor { return &bleTestClientAdaptor{ address: "01:02:03:04:05:06", - testReadCharacteristic: func(cUUID string) (data []byte, e error) { - return + testReadCharacteristic: func(cUUID string) ([]byte, error) { + return nil, nil }, - testWriteCharacteristic: func(cUUID string, data []byte) (e error) { - return + testWriteCharacteristic: func(cUUID string, data []byte) error { + return nil }, } } diff --git a/platforms/sphero/ollie/helpers_test.go b/platforms/sphero/ollie/helpers_test.go index e78091a01..031c4f922 100644 --- a/platforms/sphero/ollie/helpers_test.go +++ b/platforms/sphero/ollie/helpers_test.go @@ -18,30 +18,30 @@ type bleTestClientAdaptor struct { testWriteCharacteristic func(string, []byte) error } -func (t *bleTestClientAdaptor) Connect() (err error) { return } -func (t *bleTestClientAdaptor) Reconnect() (err error) { return } -func (t *bleTestClientAdaptor) Disconnect() (err error) { return } -func (t *bleTestClientAdaptor) Finalize() (err error) { return } +func (t *bleTestClientAdaptor) Connect() error { return nil } +func (t *bleTestClientAdaptor) Reconnect() error { return nil } +func (t *bleTestClientAdaptor) Disconnect() error { return nil } +func (t *bleTestClientAdaptor) Finalize() error { return nil } func (t *bleTestClientAdaptor) Name() string { return t.name } func (t *bleTestClientAdaptor) SetName(n string) { t.name = n } func (t *bleTestClientAdaptor) Address() string { return t.address } func (t *bleTestClientAdaptor) WithoutResponses(use bool) { t.withoutResponses = use } -func (t *bleTestClientAdaptor) ReadCharacteristic(cUUID string) (data []byte, err error) { +func (t *bleTestClientAdaptor) ReadCharacteristic(cUUID string) ([]byte, error) { t.mtx.Lock() defer t.mtx.Unlock() return t.testReadCharacteristic(cUUID) } -func (t *bleTestClientAdaptor) WriteCharacteristic(cUUID string, data []byte) (err error) { +func (t *bleTestClientAdaptor) WriteCharacteristic(cUUID string, data []byte) error { t.mtx.Lock() defer t.mtx.Unlock() return t.testWriteCharacteristic(cUUID, data) } -func (t *bleTestClientAdaptor) Subscribe(cUUID string, f func([]byte, error)) (err error) { +func (t *bleTestClientAdaptor) Subscribe(cUUID string, f func([]byte, error)) error { // TODO: implement this... - return + return nil } func (t *bleTestClientAdaptor) TestReadCharacteristic(f func(cUUID string) (data []byte, err error)) { @@ -50,7 +50,7 @@ func (t *bleTestClientAdaptor) TestReadCharacteristic(f func(cUUID string) (data t.testReadCharacteristic = f } -func (t *bleTestClientAdaptor) TestWriteCharacteristic(f func(cUUID string, data []byte) (err error)) { +func (t *bleTestClientAdaptor) TestWriteCharacteristic(f func(cUUID string, data []byte) error) { t.mtx.Lock() defer t.mtx.Unlock() t.testWriteCharacteristic = f @@ -59,11 +59,11 @@ func (t *bleTestClientAdaptor) TestWriteCharacteristic(f func(cUUID string, data func NewBleTestAdaptor() *bleTestClientAdaptor { return &bleTestClientAdaptor{ address: "01:02:03:04:05:06", - testReadCharacteristic: func(cUUID string) (data []byte, e error) { - return + testReadCharacteristic: func(cUUID string) ([]byte, error) { + return nil, nil }, - testWriteCharacteristic: func(cUUID string, data []byte) (e error) { - return + testWriteCharacteristic: func(cUUID string, data []byte) error { + return nil }, } } diff --git a/platforms/sphero/ollie/ollie_driver.go b/platforms/sphero/ollie/ollie_driver.go index 4ef37d836..d544d3a66 100644 --- a/platforms/sphero/ollie/ollie_driver.go +++ b/platforms/sphero/ollie/ollie_driver.go @@ -117,6 +117,7 @@ func (b *Driver) SetName(n string) { b.name = n } // adaptor returns BLE adaptor func (b *Driver) adaptor() ble.BLEConnector { + //nolint:forcetypeassert // ok here return b.Connection().(ble.BLEConnector) } @@ -426,25 +427,21 @@ func (b *Driver) handleLocatorDetected(data []uint8) { } func (b *Driver) handleCollisionDetected(data []uint8) { - if len(data) == ResponsePacketMaxSize { + switch len(data) { + case 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) - switch data[1] { - case 0xFE: - if data[2] == 0x07 { - // response code 7 is for a detected collision - if len(b.collisionResponse) == 0 { - b.collisionResponse = append(b.collisionResponse, data...) - } - } + if data[1] == 0xFE && data[2] == 0x07 && len(b.collisionResponse) == 0 { + // response code 7 is for a detected collision + b.collisionResponse = append(b.collisionResponse, data...) } - } else if len(data) == CollisionResponseSize-ResponsePacketMaxSize { + case CollisionResponseSize - ResponsePacketMaxSize: // if this is the remaining part of the collision response, // then make sure the header and first part of data is already received if len(b.collisionResponse) == ResponsePacketMaxSize { b.collisionResponse = append(b.collisionResponse, data...) } - } else { + default: return // not collision event } diff --git a/platforms/sphero/ollie/ollie_driver_test.go b/platforms/sphero/ollie/ollie_driver_test.go index 5294bb569..b736c0d82 100644 --- a/platforms/sphero/ollie/ollie_driver_test.go +++ b/platforms/sphero/ollie/ollie_driver_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert // ok here package ollie import ( @@ -8,6 +9,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/platforms/sphero" ) diff --git a/platforms/sphero/sphero_adaptor.go b/platforms/sphero/sphero_adaptor.go index 762662a46..d71f10666 100644 --- a/platforms/sphero/sphero_adaptor.go +++ b/platforms/sphero/sphero_adaptor.go @@ -3,9 +3,9 @@ package sphero import ( "io" - "gobot.io/x/gobot/v2" - "go.bug.st/serial" + + "gobot.io/x/gobot/v2" ) // Adaptor represents a Connection to a Sphero @@ -41,21 +41,21 @@ func (a *Adaptor) Port() string { return a.port } func (a *Adaptor) SetPort(p string) { a.port = p } // Connect initiates a connection to the Sphero. Returns true on successful connection. -func (a *Adaptor) Connect() (err error) { - sp, e := a.connect(a.Port()) - if e != nil { - return e +func (a *Adaptor) Connect() error { + sp, err := a.connect(a.Port()) + if err != nil { + return err } a.sp = sp a.connected = true - return + return nil } // Reconnect attempts to reconnect to the Sphero. If the Sphero has an active connection // it will first close that connection and then establish a new connection. // Returns true on Successful reconnection -func (a *Adaptor) Reconnect() (err error) { +func (a *Adaptor) Reconnect() error { if a.connected { if err := a.Disconnect(); err != nil { return err @@ -67,8 +67,8 @@ func (a *Adaptor) Reconnect() (err error) { // Disconnect terminates the connection to the Sphero. Returns true on successful disconnect. func (a *Adaptor) Disconnect() error { if a.connected { - if e := a.sp.Close(); e != nil { - return e + if err := a.sp.Close(); err != nil { + return err } a.connected = false } diff --git a/platforms/sphero/sphero_adaptor_test.go b/platforms/sphero/sphero_adaptor_test.go index f9e4f3c89..a364e14c0 100644 --- a/platforms/sphero/sphero_adaptor_test.go +++ b/platforms/sphero/sphero_adaptor_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/sphero/sphero_driver.go b/platforms/sphero/sphero_driver.go index b2e9d48ae..81963422e 100644 --- a/platforms/sphero/sphero_driver.go +++ b/platforms/sphero/sphero_driver.go @@ -70,6 +70,7 @@ func NewSpheroDriver(a *Adaptor) *SpheroDriver { s.AddEvent(Collision) s.AddEvent(SensorData) + //nolint:forcetypeassert // ok here s.AddCommand("SetRGB", func(params map[string]interface{}) interface{} { r := uint8(params["r"].(float64)) g := uint8(params["g"].(float64)) @@ -78,6 +79,7 @@ func NewSpheroDriver(a *Adaptor) *SpheroDriver { return nil }) + //nolint:forcetypeassert // ok here s.AddCommand("Roll", func(params map[string]interface{}) interface{} { speed := uint8(params["speed"].(float64)) heading := uint16(params["heading"].(float64)) @@ -98,30 +100,31 @@ func NewSpheroDriver(a *Adaptor) *SpheroDriver { return s.ReadLocator() }) + //nolint:forcetypeassert // ok here s.AddCommand("SetBackLED", func(params map[string]interface{}) interface{} { level := uint8(params["level"].(float64)) s.SetBackLED(level) return nil }) - + //nolint:forcetypeassert // ok here s.AddCommand("SetRotationRate", func(params map[string]interface{}) interface{} { level := uint8(params["level"].(float64)) s.SetRotationRate(level) return nil }) - + //nolint:forcetypeassert // ok here s.AddCommand("SetHeading", func(params map[string]interface{}) interface{} { heading := uint16(params["heading"].(float64)) s.SetHeading(heading) return nil }) - + //nolint:forcetypeassert // ok here s.AddCommand("SetStabilization", func(params map[string]interface{}) interface{} { on := params["enable"].(bool) s.SetStabilization(on) return nil }) - + //nolint:forcetypeassert // ok here s.AddCommand("SetDataStreaming", func(params map[string]interface{}) interface{} { N := uint16(params["N"].(float64)) M := uint16(params["M"].(float64)) @@ -132,7 +135,7 @@ func NewSpheroDriver(a *Adaptor) *SpheroDriver { s.SetDataStreaming(DataStreamingConfig{N: N, M: M, Mask2: Mask2, Pcnt: Pcnt, Mask: Mask}) return nil }) - + //nolint:forcetypeassert // ok here s.AddCommand("ConfigureLocator", func(params map[string]interface{}) interface{} { Flags := uint8(params["Flags"].(float64)) X := int16(params["X"].(float64)) @@ -156,6 +159,7 @@ func (s *SpheroDriver) SetName(n string) { s.name = n } func (s *SpheroDriver) Connection() gobot.Connection { return s.connection } func (s *SpheroDriver) adaptor() *Adaptor { + //nolint:forcetypeassert // ok here return s.Connection().(*Adaptor) } @@ -167,7 +171,7 @@ func (s *SpheroDriver) adaptor() *Adaptor { // Collision sphero.CollisionPacket - On Collision Detected // SensorData sphero.DataStreamingPacket - On Data Streaming event // Error error- On error while processing asynchronous response -func (s *SpheroDriver) Start() (err error) { +func (s *SpheroDriver) Start() error { go func() { for { packet := <-s.packetChannel @@ -223,19 +227,19 @@ func (s *SpheroDriver) Start() (err error) { s.ConfigureCollisionDetection(DefaultCollisionConfig()) s.enableStopOnDisconnect() - return + return nil } // Halt halts the SpheroDriver and sends a SpheroDriver.Stop command to the Sphero. // Returns true on successful halt. -func (s *SpheroDriver) Halt() (err error) { +func (s *SpheroDriver) Halt() error { if s.adaptor().connected { gobot.Every(10*time.Millisecond, func() { s.Stop() }) time.Sleep(1 * time.Second) } - return + return nil } // SetRGB sets the Sphero to the given r, g, and b values @@ -414,7 +418,7 @@ func (s *SpheroDriver) craftPacket(body []uint8, did byte, cid byte) *packet { / return packet } -func (s *SpheroDriver) write(packet *packet) (err error) { +func (s *SpheroDriver) write(packet *packet) error { s.mtx.Lock() defer s.mtx.Unlock() buf := append(packet.header, packet.body...) @@ -422,11 +426,13 @@ func (s *SpheroDriver) write(packet *packet) (err error) { length, err := s.adaptor().sp.Write(buf) if err != nil { return err - } else if length != len(buf) { + } + + if length != len(buf) { return errors.New("Not enough bytes written") } s.seq++ - return + return nil } func (s *SpheroDriver) calculateChecksum(packet *packet) uint8 { diff --git a/platforms/sphero/sphero_driver_test.go b/platforms/sphero/sphero_driver_test.go index 728bf3063..4004d083f 100644 --- a/platforms/sphero/sphero_driver_test.go +++ b/platforms/sphero/sphero_driver_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert // ok here package sphero import ( @@ -8,6 +9,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/sphero/sphero_packets.go b/platforms/sphero/sphero_packets.go index efac784c2..33b17c9e8 100644 --- a/platforms/sphero/sphero_packets.go +++ b/platforms/sphero/sphero_packets.go @@ -37,7 +37,8 @@ func DefaultCollisionConfig() CollisionConfig { } // CollisionConfig provides configuration for the collision detection alogorithm. -// For more information refer to the official api specification https://github.com/orbotix/DeveloperResources/blob/master/docs/Collision%20detection%201.2.pdf. +// For more information refer to the official api specification +// https://github.com/orbotix/DeveloperResources/blob/master/docs/Collision%20detection%201.2.pdf. type CollisionConfig struct { // Detection method type to use. Methods 01h and 02h are supported as // of FW ver 1.42. Use 00h to completely disable this service. @@ -73,7 +74,8 @@ type CollisionPacket struct { Timestamp uint32 } -// DefaultDataStreamingConfig returns a DataStreamingConfig with a sampling rate of 40hz, 1 sample frame per package, unlimited streaming, and will stream all available sensor information +// DefaultDataStreamingConfig returns a DataStreamingConfig with a sampling rate of 40hz, 1 sample frame per package, +// unlimited streaming, and will stream all available sensor information func DefaultDataStreamingConfig() DataStreamingConfig { return DataStreamingConfig{ N: 10, @@ -85,7 +87,8 @@ func DefaultDataStreamingConfig() DataStreamingConfig { } // DataStreamingConfig provides configuration for Sensor Data Streaming. -// For more information refer to the official api specification https://github.com/orbotix/DeveloperResources/blob/master/docs/Sphero_API_1.50.pdf page 28 +// For more information refer to the official api specification +// https://github.com/orbotix/DeveloperResources/blob/master/docs/Sphero_API_1.50.pdf page 28 type DataStreamingConfig struct { // Divisor of the maximum sensor sampling rate N uint16 diff --git a/platforms/sphero/sprkplus/helpers_test.go b/platforms/sphero/sprkplus/helpers_test.go index af6455f8a..b26be641e 100644 --- a/platforms/sphero/sprkplus/helpers_test.go +++ b/platforms/sphero/sprkplus/helpers_test.go @@ -18,30 +18,30 @@ type bleTestClientAdaptor struct { testWriteCharacteristic func(string, []byte) error } -func (t *bleTestClientAdaptor) Connect() (err error) { return } -func (t *bleTestClientAdaptor) Reconnect() (err error) { return } -func (t *bleTestClientAdaptor) Disconnect() (err error) { return } -func (t *bleTestClientAdaptor) Finalize() (err error) { return } +func (t *bleTestClientAdaptor) Connect() error { return nil } +func (t *bleTestClientAdaptor) Reconnect() error { return nil } +func (t *bleTestClientAdaptor) Disconnect() error { return nil } +func (t *bleTestClientAdaptor) Finalize() error { return nil } func (t *bleTestClientAdaptor) Name() string { return t.name } func (t *bleTestClientAdaptor) SetName(n string) { t.name = n } func (t *bleTestClientAdaptor) Address() string { return t.address } func (t *bleTestClientAdaptor) WithoutResponses(use bool) { t.withoutResponses = use } -func (t *bleTestClientAdaptor) ReadCharacteristic(cUUID string) (data []byte, err error) { +func (t *bleTestClientAdaptor) ReadCharacteristic(cUUID string) ([]byte, error) { t.mtx.Lock() defer t.mtx.Unlock() return t.testReadCharacteristic(cUUID) } -func (t *bleTestClientAdaptor) WriteCharacteristic(cUUID string, data []byte) (err error) { +func (t *bleTestClientAdaptor) WriteCharacteristic(cUUID string, data []byte) error { t.mtx.Lock() defer t.mtx.Unlock() return t.testWriteCharacteristic(cUUID, data) } -func (t *bleTestClientAdaptor) Subscribe(cUUID string, f func([]byte, error)) (err error) { +func (t *bleTestClientAdaptor) Subscribe(cUUID string, f func([]byte, error)) error { // TODO: implement this... - return + return nil } func (t *bleTestClientAdaptor) TestReadCharacteristic(f func(cUUID string) (data []byte, err error)) { @@ -50,7 +50,7 @@ func (t *bleTestClientAdaptor) TestReadCharacteristic(f func(cUUID string) (data t.testReadCharacteristic = f } -func (t *bleTestClientAdaptor) TestWriteCharacteristic(f func(cUUID string, data []byte) (err error)) { +func (t *bleTestClientAdaptor) TestWriteCharacteristic(f func(cUUID string, data []byte) error) { t.mtx.Lock() defer t.mtx.Unlock() t.testWriteCharacteristic = f @@ -59,11 +59,11 @@ func (t *bleTestClientAdaptor) TestWriteCharacteristic(f func(cUUID string, data func NewBleTestAdaptor() *bleTestClientAdaptor { return &bleTestClientAdaptor{ address: "01:02:03:04:05:06", - testReadCharacteristic: func(cUUID string) (data []byte, e error) { - return + testReadCharacteristic: func(cUUID string) ([]byte, error) { + return nil, nil }, - testWriteCharacteristic: func(cUUID string, data []byte) (e error) { - return + testWriteCharacteristic: func(cUUID string, data []byte) error { + return nil }, } } diff --git a/platforms/sphero/sprkplus/sprkplus_driver_test.go b/platforms/sphero/sprkplus/sprkplus_driver_test.go index a050e505a..67742a13a 100644 --- a/platforms/sphero/sprkplus/sprkplus_driver_test.go +++ b/platforms/sphero/sprkplus/sprkplus_driver_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/platforms/tinkerboard/adaptor.go b/platforms/tinkerboard/adaptor.go index 8b1208a65..63f8a451d 100644 --- a/platforms/tinkerboard/adaptor.go +++ b/platforms/tinkerboard/adaptor.go @@ -5,6 +5,7 @@ import ( "sync" multierror "github.com/hashicorp/go-multierror" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/platforms/adaptors" "gobot.io/x/gobot/v2/system" @@ -154,14 +155,14 @@ func (c *Adaptor) translatePWMPin(id string) (string, int, error) { return path, pinInfo.channel, nil } -func (p pwmPinDefinition) findPWMDir(sys *system.Accesser) (dir string, err error) { +func (p pwmPinDefinition) findPWMDir(sys *system.Accesser) (string, error) { items, _ := sys.Find(p.dir, p.dirRegexp) if len(items) == 0 { return "", fmt.Errorf("No path found for PWM directory pattern, '%s' in path '%s'. See README.md for activation", p.dirRegexp, p.dir) } - dir = items[0] + dir := items[0] info, err := sys.Stat(dir) if err != nil { return "", fmt.Errorf("Error (%v) on access '%s'", err, dir) @@ -170,5 +171,5 @@ func (p pwmPinDefinition) findPWMDir(sys *system.Accesser) (dir string, err erro return "", fmt.Errorf("The item '%s' is not a directory, which is not expected", dir) } - return + return dir, nil } diff --git a/platforms/tinkerboard/adaptor_test.go b/platforms/tinkerboard/adaptor_test.go index 4835b66a3..f00374fde 100644 --- a/platforms/tinkerboard/adaptor_test.go +++ b/platforms/tinkerboard/adaptor_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/gpio" "gobot.io/x/gobot/v2/drivers/i2c" @@ -188,7 +189,7 @@ func TestFinalizeErrorAfterGPIO(t *testing.T) { fs.WithWriteError = true err := a.Finalize() - assert.Contains(t, err.Error(), "write error") + require.ErrorContains(t, err, "write error") } func TestFinalizeErrorAfterPWM(t *testing.T) { @@ -200,7 +201,7 @@ func TestFinalizeErrorAfterPWM(t *testing.T) { fs.WithWriteError = true err := a.Finalize() - assert.Contains(t, err.Error(), "write error") + require.ErrorContains(t, err, "write error") } func TestSpiDefaultValues(t *testing.T) { @@ -232,7 +233,7 @@ func TestI2cFinalizeWithErrors(t *testing.T) { // act err = a.Finalize() // assert - assert.Contains(t, err.Error(), "close error") + require.ErrorContains(t, err, "close error") } func Test_validateSpiBusNumber(t *testing.T) { diff --git a/platforms/upboard/up2/adaptor.go b/platforms/upboard/up2/adaptor.go index 5f0360b00..d4a80660c 100644 --- a/platforms/upboard/up2/adaptor.go +++ b/platforms/upboard/up2/adaptor.go @@ -7,6 +7,7 @@ import ( "sync" multierror "github.com/hashicorp/go-multierror" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/platforms/adaptors" "gobot.io/x/gobot/v2/system" diff --git a/platforms/upboard/up2/adaptor_test.go b/platforms/upboard/up2/adaptor_test.go index 82faaa203..0c8c0f348 100644 --- a/platforms/upboard/up2/adaptor_test.go +++ b/platforms/upboard/up2/adaptor_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/drivers/gpio" "gobot.io/x/gobot/v2/drivers/i2c" @@ -119,7 +120,7 @@ func TestFinalizeErrorAfterGPIO(t *testing.T) { fs.WithWriteError = true err := a.Finalize() - assert.Contains(t, err.Error(), "write error") + require.ErrorContains(t, err, "write error") } func TestFinalizeErrorAfterPWM(t *testing.T) { @@ -132,7 +133,7 @@ func TestFinalizeErrorAfterPWM(t *testing.T) { fs.WithWriteError = true err := a.Finalize() - assert.Contains(t, err.Error(), "write error") + require.ErrorContains(t, err, "write error") } func TestSpiDefaultValues(t *testing.T) { @@ -194,7 +195,7 @@ func TestI2cFinalizeWithErrors(t *testing.T) { // act err = a.Finalize() // assert - assert.Contains(t, err.Error(), "close error") + require.ErrorContains(t, err, "close error") } func Test_validateI2cBusNumber(t *testing.T) { diff --git a/robot.go b/robot.go index 647cd8b77..6547bbfa4 100644 --- a/robot.go +++ b/robot.go @@ -71,7 +71,11 @@ func (r *Robots) Len() int { func (r *Robots) Start(args ...interface{}) error { autoRun := true if args[0] != nil { - autoRun = args[0].(bool) + var ok bool + if autoRun, ok = args[0].(bool); !ok { + // we treat this as false + autoRun = false + } } for _, robot := range *r { if err := robot.Start(autoRun); err != nil { @@ -122,23 +126,23 @@ func NewRobot(v ...interface{}) *Robot { } for i := range v { - switch v[i].(type) { + switch val := v[i].(type) { case string: - r.Name = v[i].(string) + r.Name = val case []Connection: log.Println("Initializing connections...") - for _, connection := range v[i].([]Connection) { + for _, connection := range val { c := r.AddConnection(connection) log.Println("Initializing connection", c.Name(), "...") } case []Device: log.Println("Initializing devices...") - for _, device := range v[i].([]Device) { + for _, device := range val { d := r.AddDevice(device) log.Println("Initializing device", d.Name(), "...") } case func(): - r.Work = v[i].(func()) + r.Work = val } } @@ -158,7 +162,11 @@ func NewRobot(v ...interface{}) *Robot { // connections and devices on first error. func (r *Robot) Start(args ...interface{}) error { if len(args) > 0 && args[0] != nil { - r.AutoRun = args[0].(bool) + var ok bool + if r.AutoRun, ok = args[0].(bool); !ok { + // we treat this as false + r.AutoRun = false + } } log.Println("Starting Robot", r.Name, "...") if err := r.Connections().Start(); err != nil { @@ -216,7 +224,7 @@ func (r *Robot) Stop() error { // Running returns if the Robot is currently started or not func (r *Robot) Running() bool { - return r.running.Load().(bool) + return r.running.Load().(bool) //nolint:forcetypeassert // no error return value, so there is no better way } // Devices returns all devices associated with this Robot. diff --git a/robot_work.go b/robot_work.go index b3a4e4ac7..11f74ea90 100644 --- a/robot_work.go +++ b/robot_work.go @@ -47,7 +47,7 @@ type RobotWork struct { id uuid.UUID kind string tickCount int - ctx context.Context + ctx context.Context //nolint:containedctx // done by intention cancelFunc context.CancelFunc function func() ticker *time.Ticker diff --git a/system/digitalpin_access_test.go b/system/digitalpin_access_test.go index beda36d0c..92db6f9df 100644 --- a/system/digitalpin_access_test.go +++ b/system/digitalpin_access_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert // ok here package system import ( diff --git a/system/digitalpin_config.go b/system/digitalpin_config.go index 76e880283..f41227887 100644 --- a/system/digitalpin_config.go +++ b/system/digitalpin_config.go @@ -243,6 +243,8 @@ func (d *digitalPinConfig) SetEventHandlerForEdge( // the adaptor. E.g. sysfs driver in gobot has not implemented edge detection yet. The function is only useful // together with SetEventHandlerForEdge() and its corresponding With*() functions. // The function is intended to use by WithPinPollForEdgeDetection(). +// +//nolint:nonamedreturns // useful here func (d *digitalPinConfig) SetPollForEdgeDetection( pollInterval time.Duration, pollQuitChan chan struct{}, diff --git a/system/digitalpin_config_test.go b/system/digitalpin_config_test.go index c14d6fb5b..82a63c9fe 100644 --- a/system/digitalpin_config_test.go +++ b/system/digitalpin_config_test.go @@ -5,6 +5,7 @@ import ( "time" "github.com/stretchr/testify/assert" + "gobot.io/x/gobot/v2" ) diff --git a/system/digitalpin_gpiod.go b/system/digitalpin_gpiod.go index c161dc00f..7ebe9f85c 100644 --- a/system/digitalpin_gpiod.go +++ b/system/digitalpin_gpiod.go @@ -8,6 +8,7 @@ import ( "time" "github.com/warthog618/gpiod" + "gobot.io/x/gobot/v2" ) diff --git a/system/digitalpin_gpiod_test.go b/system/digitalpin_gpiod_test.go index a6e086202..226db6576 100644 --- a/system/digitalpin_gpiod_test.go +++ b/system/digitalpin_gpiod_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -257,7 +258,7 @@ func TestWriteGpiod(t *testing.T) { // assert if tc.wantErr != nil { for _, want := range tc.wantErr { - assert.Contains(t, err.Error(), want) + require.ErrorContains(t, err, want) } } else { require.NoError(t, err) @@ -292,7 +293,7 @@ func TestReadGpiod(t *testing.T) { // assert if tc.wantErr != nil { for _, want := range tc.wantErr { - assert.Contains(t, err.Error(), want) + require.ErrorContains(t, err, want) } } else { require.NoError(t, err) diff --git a/system/digitalpin_mock.go b/system/digitalpin_mock.go index 440df69ea..c85fa345a 100644 --- a/system/digitalpin_mock.go +++ b/system/digitalpin_mock.go @@ -37,8 +37,8 @@ func (d *digitalPinMock) Write(b int) error { } // Read reads the given value from character device -func (d *digitalPinMock) Read() (n int, err error) { - return 0, err +func (d *digitalPinMock) Read() (int, error) { + return 0, nil } // Export sets the pin as exported with the configured direction diff --git a/system/digitalpin_sysfs.go b/system/digitalpin_sysfs.go index 7829befe4..9c0e89c8c 100644 --- a/system/digitalpin_sysfs.go +++ b/system/digitalpin_sysfs.go @@ -89,9 +89,9 @@ func (d *digitalPinSysfs) Unexport() error { err = writeFile(unexport, []byte(d.pin)) if err != nil { - // If EINVAL then the pin is reserved in the system and can't be unexported - e, ok := err.(*os.PathError) - if !ok || e.Err != Syscall_EINVAL { + // If EINVAL then the pin is reserved in the system and can't be unexported, we suppress the error + var pathError *os.PathError + if !(errors.As(err, &pathError) && errors.Is(err, Syscall_EINVAL)) { return err } } @@ -123,9 +123,9 @@ func (d *digitalPinSysfs) reconfigure() error { err = writeFile(exportFile, []byte(d.pin)) if err != nil { - // If EBUSY then the pin has already been exported - e, ok := err.(*os.PathError) - if !ok || e.Err != Syscall_EBUSY { + // If EBUSY then the pin has already been exported, we suppress the error + var pathError *os.PathError + if !(errors.As(err, &pathError) && errors.Is(err, Syscall_EBUSY)) { return err } } @@ -196,11 +196,9 @@ func (d *digitalPinSysfs) reconfigure() error { err = startEdgePolling(d.label, d.Read, d.pollInterval, d.edge, d.edgeEventHandler, d.pollQuitChan) } } - } else { + } else if d.drive != digitalPinDrivePushPull && systemSysfsDebug { // configure drive (unsupported) - if d.drive != digitalPinDrivePushPull && systemSysfsDebug { - log.Printf("drive options (%d) are not supported by sysfs\n", d.drive) - } + log.Printf("drive options (%d) are not supported by sysfs\n", d.drive) } if err != nil { diff --git a/system/digitalpin_sysfs_test.go b/system/digitalpin_sysfs_test.go index 6efa8117f..6f6473ac9 100644 --- a/system/digitalpin_sysfs_test.go +++ b/system/digitalpin_sysfs_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -387,7 +388,9 @@ func TestDigitalPinSysfs(t *testing.T) { } err = pin.Unexport() - require.ErrorContains(t, err.(*os.PathError).Err, "write error") + var pathError *os.PathError + require.ErrorAs(t, err, &pathError) + require.ErrorContains(t, err, "write error") } func TestDigitalPinUnexportErrorSysfs(t *testing.T) { diff --git a/system/fs.go b/system/fs.go index 2bdfd365d..829dc6ef6 100644 --- a/system/fs.go +++ b/system/fs.go @@ -10,7 +10,7 @@ import ( type nativeFilesystem struct{} // openFile calls os.OpenFile(). -func (fs *nativeFilesystem) openFile(name string, flag int, perm os.FileMode) (file File, err error) { +func (fs *nativeFilesystem) openFile(name string, flag int, perm os.FileMode) (File, error) { return os.OpenFile(name, flag, perm) } diff --git a/system/fs_mock.go b/system/fs_mock.go index f7f1a5f1f..d91c4383e 100644 --- a/system/fs_mock.go +++ b/system/fs_mock.go @@ -42,7 +42,7 @@ var ( ) // Write writes string(b) to f.Contents -func (f *MockFile) Write(b []byte) (n int, err error) { +func (f *MockFile) Write(b []byte) (int, error) { if f.fs.WithWriteError { return 0, errWrite } @@ -50,24 +50,24 @@ func (f *MockFile) Write(b []byte) (n int, err error) { } // Seek seeks to a specific offset in a file -func (f *MockFile) Seek(offset int64, whence int) (ret int64, err error) { +func (f *MockFile) Seek(offset int64, whence int) (int64, error) { return offset, nil } // WriteString writes s to f.Contents -func (f *MockFile) WriteString(s string) (ret int, err error) { +func (f *MockFile) WriteString(s string) (int, error) { f.Contents = s f.Seq = f.fs.next() return len(s), nil } // Sync implements the File interface Sync function -func (f *MockFile) Sync() (err error) { +func (f *MockFile) Sync() error { return nil } // Read copies b bytes from f.Contents -func (f *MockFile) Read(b []byte) (n int, err error) { +func (f *MockFile) Read(b []byte) (int, error) { if f.fs.WithReadError { return 0, errRead } @@ -83,7 +83,7 @@ func (f *MockFile) Read(b []byte) (n int, err error) { } // ReadAt calls MockFile.Read -func (f *MockFile) ReadAt(b []byte, off int64) (n int, err error) { +func (f *MockFile) ReadAt(b []byte, off int64) (int, error) { return f.Read(b) } @@ -119,7 +119,7 @@ func newMockFilesystem(items []string) *MockFilesystem { } // OpenFile opens file name from fs.Files, if the file does not exist it returns an os.PathError -func (fs *MockFilesystem) openFile(name string, _ int, _ os.FileMode) (file File, err error) { +func (fs *MockFilesystem) openFile(name string, _ int, _ os.FileMode) (File, error) { f, ok := fs.Files[name] if ok { f.Opened = true diff --git a/system/i2c_device.go b/system/i2c_device.go index 3b635e03d..8c8e9f077 100644 --- a/system/i2c_device.go +++ b/system/i2c_device.go @@ -111,7 +111,7 @@ func (d *i2cDevice) ReadByte(address int) (byte, error) { } // ReadByteData reads a byte from the given register of an i2c device. -func (d *i2cDevice) ReadByteData(address int, reg uint8) (val uint8, err error) { +func (d *i2cDevice) ReadByteData(address int, reg uint8) (uint8, error) { d.mutex.Lock() defer d.mutex.Unlock() @@ -120,12 +120,12 @@ func (d *i2cDevice) ReadByteData(address int, reg uint8) (val uint8, err error) } var data uint8 = 0xFD // set value for debugging purposes - err = d.smbusAccess(address, I2C_SMBUS_READ, reg, I2C_SMBUS_BYTE_DATA, unsafe.Pointer(&data)) + err := d.smbusAccess(address, I2C_SMBUS_READ, reg, I2C_SMBUS_BYTE_DATA, unsafe.Pointer(&data)) return data, err } // ReadWordData reads a 16 bit value starting from the given register of an i2c device. -func (d *i2cDevice) ReadWordData(address int, reg uint8) (val uint16, err error) { +func (d *i2cDevice) ReadWordData(address int, reg uint8) (uint16, error) { d.mutex.Lock() defer d.mutex.Unlock() @@ -134,7 +134,7 @@ func (d *i2cDevice) ReadWordData(address int, reg uint8) (val uint16, err error) } var data uint16 = 0xFFFE // set value for debugging purposes - err = d.smbusAccess(address, I2C_SMBUS_READ, reg, I2C_SMBUS_WORD_DATA, unsafe.Pointer(&data)) + err := d.smbusAccess(address, I2C_SMBUS_READ, reg, I2C_SMBUS_WORD_DATA, unsafe.Pointer(&data)) return data, err } @@ -241,7 +241,7 @@ func (d *i2cDevice) WriteBytes(address int, data []byte) error { } // Read implements direct I2C read operations. -func (d *i2cDevice) Read(address int, b []byte) (n int, err error) { +func (d *i2cDevice) Read(address int, b []byte) (int, error) { d.mutex.Lock() defer d.mutex.Unlock() @@ -249,7 +249,7 @@ func (d *i2cDevice) Read(address int, b []byte) (n int, err error) { } // Write implements the io.ReadWriteCloser method by direct I2C write operations. -func (d *i2cDevice) Write(address int, b []byte) (n int, err error) { +func (d *i2cDevice) Write(address int, b []byte) (int, error) { d.mutex.Lock() defer d.mutex.Unlock() @@ -288,8 +288,8 @@ func (d *i2cDevice) writeBytes(address int, data []byte) error { return nil } -func (d *i2cDevice) write(address int, b []byte) (n int, err error) { - if err = d.setAddress(address); err != nil { +func (d *i2cDevice) write(address int, b []byte) (int, error) { + if err := d.setAddress(address); err != nil { return 0, err } if err := d.openFileLazy("Write"); err != nil { @@ -309,8 +309,8 @@ func (d *i2cDevice) readAndCheckCount(address int, data []byte) error { return nil } -func (d *i2cDevice) read(address int, b []byte) (n int, err error) { - if err = d.setAddress(address); err != nil { +func (d *i2cDevice) read(address int, b []byte) (int, error) { + if err := d.setAddress(address); err != nil { return 0, err } if err := d.openFileLazy("Read"); err != nil { @@ -378,7 +378,7 @@ func (d *i2cDevice) setAddress(address int) error { return nil } -func (d *i2cDevice) syscallIoctl(signal uintptr, payload unsafe.Pointer, address int, sender string) (err error) { +func (d *i2cDevice) syscallIoctl(signal uintptr, payload unsafe.Pointer, address int, sender string) error { if err := d.openFileLazy(sender); err != nil { return err } @@ -389,12 +389,13 @@ func (d *i2cDevice) syscallIoctl(signal uintptr, payload unsafe.Pointer, address return nil } -func (d *i2cDevice) openFileLazy(sender string) (err error) { //nolint:unparam // useful for debugging +func (d *i2cDevice) openFileLazy(sender string) 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 // helpful and we drop it to the default "0" used by normal Open(). if d.file == nil { + var err error if d.file, err = d.fs.openFile(d.location, os.O_RDWR, 0); err != nil { return err } diff --git a/system/i2c_device_test.go b/system/i2c_device_test.go index 78e59823d..b7b473885 100644 --- a/system/i2c_device_test.go +++ b/system/i2c_device_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) @@ -18,6 +19,7 @@ func getSyscallFuncImpl( // bit 0: error on function query // bit 1: error on set address // bit 2: error on command + //nolint:nonamedreturns // useful here return func(trap, a1, a2 uintptr, a3 unsafe.Pointer) (r1, r2 uintptr, err SyscallErrno) { // function query if (trap == Syscall_SYS_IOCTL) && (a2 == I2C_FUNCS) { diff --git a/system/pwmpin_sysfs.go b/system/pwmpin_sysfs.go index 2980a977f..a038e469f 100644 --- a/system/pwmpin_sysfs.go +++ b/system/pwmpin_sysfs.go @@ -2,6 +2,7 @@ package system import ( "bytes" + "errors" "fmt" "os" "path" @@ -47,9 +48,9 @@ func newPWMPinSysfs(fs filesystem, path string, pin int, polNormIdent string, po func (p *pwmPinSysFs) Export() error { _, err := p.write(p.fs, p.pwmExportPath(), []byte(p.pin)) if err != nil { - // If EBUSY then the pin has already been exported - e, ok := err.(*os.PathError) - if !ok || e.Err != Syscall_EBUSY { + // If EBUSY then the pin has already been exported, we suppress the error + var pathError *os.PathError + if !(errors.As(err, &pathError) && errors.Is(err, Syscall_EBUSY)) { return fmt.Errorf(pwmPinErrorPattern, "Export", p.pin, err) } } diff --git a/system/pwmpin_sysfs_test.go b/system/pwmpin_sysfs_test.go index c0ba78967..b4c1f82c9 100644 --- a/system/pwmpin_sysfs_test.go +++ b/system/pwmpin_sysfs_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gobot.io/x/gobot/v2" ) diff --git a/system/spi_access.go b/system/spi_access.go index 5b1feb482..d7fdd1bef 100644 --- a/system/spi_access.go +++ b/system/spi_access.go @@ -12,7 +12,10 @@ type gpioSpiAccess struct { cfg spiGpioConfig } -func (*periphioSpiAccess) createDevice(busNum, chipNum, mode, bits int, maxSpeed int64) (gobot.SpiSystemDevicer, error) { +func (*periphioSpiAccess) createDevice( + busNum, chipNum, mode, bits int, + maxSpeed int64, +) (gobot.SpiSystemDevicer, error) { return newSpiPeriphIo(busNum, chipNum, mode, bits, maxSpeed) } @@ -24,7 +27,10 @@ func (psa *periphioSpiAccess) isSupported() bool { return true } -func (gsa *gpioSpiAccess) createDevice(busNum, chipNum, mode, bits int, maxSpeed int64) (gobot.SpiSystemDevicer, error) { +func (gsa *gpioSpiAccess) createDevice( + busNum, chipNum, mode, bits int, + maxSpeed int64, +) (gobot.SpiSystemDevicer, error) { return newSpiGpio(gsa.cfg, maxSpeed) } diff --git a/system/spi_gpio.go b/system/spi_gpio.go index 68c7c0016..5a21ff7d2 100644 --- a/system/spi_gpio.go +++ b/system/spi_gpio.go @@ -5,6 +5,7 @@ import ( "time" "github.com/hashicorp/go-multierror" + "gobot.io/x/gobot/v2" ) diff --git a/system/spi_mock.go b/system/spi_mock.go index f78bb41a6..b4c63b14d 100644 --- a/system/spi_mock.go +++ b/system/spi_mock.go @@ -17,7 +17,10 @@ type MockSpiAccess struct { sysdev *spiMock } -func (spi *MockSpiAccess) createDevice(busNum, chipNum, mode, bits int, maxSpeed int64) (gobot.SpiSystemDevicer, error) { +func (spi *MockSpiAccess) createDevice( + busNum, chipNum, mode, bits int, + maxSpeed int64, +) (gobot.SpiSystemDevicer, error) { spi.busNum = busNum spi.chipNum = chipNum spi.mode = mode diff --git a/system/syscall.go b/system/syscall.go index b90b1e976..41f29441a 100644 --- a/system/syscall.go +++ b/system/syscall.go @@ -29,6 +29,8 @@ type nativeSyscall struct{} // detect this problem and this unpack procedure would cause unpredictable results. // So the decision was taken to give the address here as a separate parameter, although it is not used in every call. // Note also, that the size of the address variable at Kernel side is u16, therefore uint16 is used here. +// +//nolint:nonamedreturns // useful here func (sys *nativeSyscall) syscall( trap uintptr, f File, diff --git a/system/syscall_mock.go b/system/syscall_mock.go index 1be3ffeba..1f77f2d11 100644 --- a/system/syscall_mock.go +++ b/system/syscall_mock.go @@ -17,6 +17,8 @@ type mockSyscall struct { } // Syscall calls the user defined implementation, used for tests, implements the SystemCaller interface +// +//nolint:nonamedreturns // useful here func (sys *mockSyscall) syscall( trap uintptr, f File, diff --git a/system/system.go b/system/system.go index 30ae3f39e..6e53fe144 100644 --- a/system/system.go +++ b/system/system.go @@ -13,7 +13,7 @@ const systemDebug = false type File interface { Write(b []byte) (n int, err error) WriteString(s string) (ret int, err error) - Sync() (err error) + Sync() error Read(b []byte) (n int, err error) ReadAt(b []byte, off int64) (n int, err error) Seek(offset int64, whence int) (ret int64, err error) diff --git a/system/system_test.go b/system/system_test.go index b29bd52d3..0edeab0da 100644 --- a/system/system_test.go +++ b/system/system_test.go @@ -1,3 +1,4 @@ +//nolint:forcetypeassert // ok here package system import ( diff --git a/utils.go b/utils.go index 5223c7160..36e58bb8d 100644 --- a/utils.go +++ b/utils.go @@ -46,11 +46,12 @@ func FromScale(input, min, max float64) float64 { // If input is greater than max then ToScale returns max func ToScale(input, min, max float64) float64 { i := input*(math.Max(min, max)-math.Min(min, max)) + math.Min(min, max) - if i < math.Min(min, max) { + switch { + case i < math.Min(min, max): return math.Min(min, max) - } else if i > math.Max(min, max) { + case i > math.Max(min, max): return math.Max(min, max) - } else { + default: return i } }