From bf2de620fa3abd2648183825eb69c99b5a6c43d1 Mon Sep 17 00:00:00 2001 From: Sebastian Plattner Date: Sat, 30 Sep 2023 12:51:37 +0200 Subject: [PATCH] fix: Lint errors and introduce lint in action --- .github/workflows/lint.yaml | 30 ++++ .github/workflows/{main.yml => main.yaml} | 32 ---- pkg/client/deconzclient.go | 34 +++-- pkg/client/denonavrclient.go | 35 +++-- pkg/client/shellyclient.go | 34 ++--- pkg/client/tasmotaclient.go | 34 ++--- pkg/cmd/deconz/deconz.go | 4 +- pkg/cmd/denonavr/denonavr.go | 4 +- pkg/cmd/shelly/shelly.go | 4 +- pkg/cmd/tasmota/tasmota.go | 4 +- pkg/cmd/ucrt/ucrt.go | 78 +++++++--- pkg/deconz/device.go | 10 +- pkg/deconz/group.go | 14 +- pkg/deconz/types.go | 2 +- pkg/deconz/websocket.go | 12 +- pkg/denonavr/cursor.go | 10 +- pkg/denonavr/denonavr.go | 31 ++-- pkg/denonavr/power.go | 9 +- pkg/denonavr/status.go | 3 + pkg/entities/climate.go | 42 +++--- pkg/entities/cover.go | 36 ++--- pkg/entities/entities.go | 2 +- pkg/entities/light.go | 26 ++-- pkg/entities/media_player.go | 174 +++++++++++----------- pkg/entities/sensor.go | 18 +-- pkg/entities/switch.go | 8 +- pkg/integration/device.go | 6 +- pkg/integration/events.go | 42 ++++-- pkg/integration/integration.go | 6 +- pkg/integration/register.go | 7 +- pkg/integration/requests.go | 44 ++++-- pkg/integration/response.go | 8 +- pkg/integration/settingtypes.go | 2 +- pkg/integration/types.go | 20 +-- pkg/integration/websocket.go | 13 +- pkg/shelly/shelly.go | 4 +- 36 files changed, 500 insertions(+), 342 deletions(-) create mode 100644 .github/workflows/lint.yaml rename .github/workflows/{main.yml => main.yaml} (56%) diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml new file mode 100644 index 0000000..0e82d20 --- /dev/null +++ b/.github/workflows/lint.yaml @@ -0,0 +1,30 @@ +name: Lint + +on: + pull_request: + push: + branches: + - main + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Determine Go version from go.mod + run: echo "GO_VERSION=$(go mod edit -json | jq -r .Go)" >> $GITHUB_ENV + + - uses: actions/setup-go@v3 + with: + go-version: ${{ env.GO_VERSION }} + + - uses: actions/cache@v3 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + + - name: Run linters + run: make lint \ No newline at end of file diff --git a/.github/workflows/main.yml b/.github/workflows/main.yaml similarity index 56% rename from .github/workflows/main.yml rename to .github/workflows/main.yaml index 11536e3..b0085b6 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yaml @@ -52,14 +52,6 @@ jobs: username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - # Extract metadata (tags, labels) for Docker - # https://github.com/docker/metadata-action - # - name: Extract Docker metadata - # id: meta - # uses: docker/metadata-action@96383f45573cb7f253c731d3b3ab81c87ef81934 # v5.0.0 - # with: - # images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} - - name: Build docker images run: make docker-build -e IMG_TAG=${GITHUB_REF#refs/heads/} @@ -68,27 +60,3 @@ jobs: - name: Create & Push docker manifrst run: make docker-manifest -e IMG_TAG=${GITHUB_REF#refs/heads/} - - # Build and push Docker image with Buildx (don't push on PR) - # https://github.com/docker/build-push-action - # - name: Build and push Docker image - # id: build-and-push - # uses: docker/build-push-action@0565240e2d4ab88bba5387d719585280857ece09 # v5.0.0 - # with: - # context: . - # file: build/Dockerfile.multistage - # platforms: linux/amd64,linux/arm64 - # push: ${{ github.event_name != 'pull_request' }} - # tags: ${{ steps.meta.outputs.tags }} - # labels: ${{ steps.meta.outputs.labels }} - # cache-from: type=gha - # cache-to: type=gha,mode=max - # build-args: | - # GO_VERSION=${{ env.GO_VERSION }} - - - name: Bump version and push tag - id: tag_version - uses: mathieudutour/github-tag-action@v6.1 - with: - github_token: ${{ secrets.GH_PAT }} - default_bump: false \ No newline at end of file diff --git a/pkg/client/deconzclient.go b/pkg/client/deconzclient.go index fa9e8f1..4a6dbf0 100644 --- a/pkg/client/deconzclient.go +++ b/pkg/client/deconzclient.go @@ -115,7 +115,7 @@ func (c *DeconzClient) handleSetDriverUserData(user_data map[string]string, conf if err != nil { log.WithError(err).Debug("Failed to get new api Key") - c.IntegrationDriver.SetDriverSetupState(integration.StopEvent, integration.ErrorDeviceState, integration.AuthErrorError, nil) + c.IntegrationDriver.SetDriverSetupState(integration.StopEvent, integration.ErrorState, integration.AuthErrorError, nil) return } @@ -232,7 +232,9 @@ func (c *DeconzClient) handleNewSensorDeviceDiscovered(device *deconz.DeconzDevi }) - c.IntegrationDriver.AddEntity(sensor) + if err := c.IntegrationDriver.AddEntity(sensor); err != nil { + log.WithError(err).Error("Cannot add entity") + } } } @@ -357,7 +359,9 @@ func (c *DeconzClient) handleNewLightDeviceDiscovered(device *deconz.DeconzDevic }) - c.IntegrationDriver.AddEntity(light) + if err := c.IntegrationDriver.AddEntity(light); err != nil { + log.WithError(err).Error("Cannot add entity") + } } func (c *DeconzClient) handleNewGroupDeviceDiscovered(device *deconz.DeconzDevice) { @@ -440,9 +444,13 @@ func (c *DeconzClient) handleNewGroupDeviceDiscovered(device *deconz.DeconzDevic group.AddCommand(entities.ToggleLightEntityCommand, func(entity entities.LightEntity, params map[string]interface{}) int { if device.IsOn() { - device.TurnOff() + if err := device.TurnOff(); err != nil { + return 404 + } } else { - device.TurnOn() + if err := device.TurnOn(); err != nil { + return 404 + } } return 200 }) @@ -495,7 +503,9 @@ func (c *DeconzClient) handleNewGroupDeviceDiscovered(device *deconz.DeconzDevic }) - c.IntegrationDriver.AddEntity(group) + if err := c.IntegrationDriver.AddEntity(group); err != nil { + log.WithError(err).Error("Cannot add entity") + } } func (c *DeconzClient) handleNewDeviceDiscovered(device *deconz.DeconzDevice) { @@ -527,11 +537,17 @@ func (c *DeconzClient) handleRemoveDevice(device *deconz.DeconzDevice) { switch device.Type { case deconz.SensorDeconzDeviceType: - c.IntegrationDriver.RemoveEntityByID(fmt.Sprintf("sensor%d", device.GetID())) + if err := c.IntegrationDriver.RemoveEntityByID(fmt.Sprintf("sensor%d", device.GetID())); err != nil { + log.WithError(err).Error("Cannot remove Entity") + } case deconz.LightDeconzDeviceType: - c.IntegrationDriver.RemoveEntityByID(fmt.Sprintf("light%d", device.GetID())) + if err := c.IntegrationDriver.RemoveEntityByID(fmt.Sprintf("light%d", device.GetID())); err != nil { + log.WithError(err).Error("Cannot remove Entity") + } case deconz.GroupDeconzDeviceType: - c.IntegrationDriver.RemoveEntityByID(fmt.Sprintf("group%d", device.GetID())) + if err := c.IntegrationDriver.RemoveEntityByID(fmt.Sprintf("group%d", device.GetID())); err != nil { + log.WithError(err).Error("Cannot remove Entity") + } } } diff --git a/pkg/client/denonavrclient.go b/pkg/client/denonavrclient.go index 419e0d0..317fab5 100644 --- a/pkg/client/denonavrclient.go +++ b/pkg/client/denonavrclient.go @@ -85,17 +85,28 @@ func (c *DenonAVRClient) initDenonAVRClient() { c.mediaPlayer.AddFeature(entities.UnmuteMediaPlayerEntityFeatures) c.mediaPlayer.AddFeature(entities.MuteToggleMediaPlayerEntityFeatures) c.mediaPlayer.AddFeature(entities.SelectSourceMediaPlayerEntityFeatures) - c.mediaPlayer.AddFeature(entities.SelectSoundModeMediaPlayerEntityCommand) + c.mediaPlayer.AddFeature(entities.SelectSoundModeMediaPlayerEntityFeatures) c.mediaPlayer.AddFeature(entities.DPadMediaPlayerEntityFeatures) - c.IntegrationDriver.AddEntity(c.mediaPlayer) + + if err := c.IntegrationDriver.AddEntity(c.mediaPlayer); err != nil { + log.WithError(err).Error("Cannot add Entity") + } // Butons c.moni1Button = entities.NewButtonEntity("moni1", entities.LanguageText{En: "Monitor Out 1"}, "") - c.IntegrationDriver.AddEntity(c.moni1Button) + if err := c.IntegrationDriver.AddEntity(c.moni1Button); err != nil { + log.WithError(err).Error("Cannot add Entity") + } + c.moni2Button = entities.NewButtonEntity("moni2", entities.LanguageText{En: "Monitor Out 2"}, "") - c.IntegrationDriver.AddEntity(c.moni2Button) + if err := c.IntegrationDriver.AddEntity(c.moni2Button); err != nil { + log.WithError(err).Error("Cannot add Entity") + } + c.moniAutoButton = entities.NewButtonEntity("moniauto", entities.LanguageText{En: "Monitor Out Auto"}, "") - c.IntegrationDriver.AddEntity(c.moniAutoButton) + if err := c.IntegrationDriver.AddEntity(c.moniAutoButton); err != nil { + log.WithError(err).Error("Cannot add Entity") + } } @@ -167,7 +178,7 @@ func (c *DenonAVRClient) configureDenon() { volume = s } - attributes[entities.VolumeMediaPlayerEntityAttribute] = volume + 80 + attributes[string(entities.VolumeMediaPlayerEntityAttribute)] = volume + 80 c.mediaPlayer.SetAttributes(attributes) }) @@ -326,14 +337,10 @@ func (c *DenonAVRClient) denonClientLoop() { // Run Client Loop to handle entity changes from device for { - select { - case msg := <-c.messages: - - switch msg { - case "disconnect": - return - } - + msg := <-c.messages + switch msg { + case "disconnect": + return } } diff --git a/pkg/client/shellyclient.go b/pkg/client/shellyclient.go index b6c8ab1..15576ea 100644 --- a/pkg/client/shellyclient.go +++ b/pkg/client/shellyclient.go @@ -178,11 +178,11 @@ func (c *ShellyClient) handleNewDeviceDiscovered(device *shelly.ShellyDevice) { shellySwitch := entities.NewSwitchEntity(device.Id, entities.LanguageText{En: "Shelly " + device.Id}, "") shellySwitch.AddFeature(entities.OnOffSwitchEntityyFeatures) - shellySwitch.AddFeature(entities.ToggleSwitchEntityCommand) + shellySwitch.AddFeature(entities.ToggleSwitchEntityyFeatures) shellySwitch.MapCommand(entities.OnSwitchEntityCommand, device.TurnOn) shellySwitch.MapCommand(entities.OffSwitchEntityCommand, device.TurnOff) - shellySwitch.MapCommand(entities.ToggleLightEntityCommand, device.Toggle) + shellySwitch.MapCommand(entities.ToggleSwitchEntityCommand, device.Toggle) device.AddMsgReceivedFunc("relay/0", func(msg []byte) { @@ -198,17 +198,19 @@ func (c *ShellyClient) handleNewDeviceDiscovered(device *shelly.ShellyDevice) { shellySwitch.SetAttributes(attributes) }) - c.IntegrationDriver.AddEntity(shellySwitch) + if err := c.IntegrationDriver.AddEntity(shellySwitch); err != nil { + log.WithError(err).Error("Cannot add Entity") + } } -func (c *ShellyClient) handleRemoveDevice(device *shelly.ShellyDevice) { - log.WithFields(log.Fields{ - "ID": device.Id, - "IP Address": device.IPAddress, - "MAC Address": device.MACAddress, - }).Debug("New Shelly Device not available anymore") -} +// func (c *ShellyClient) handleRemoveDevice(device *shelly.ShellyDevice) { +// log.WithFields(log.Fields{ +// "ID": device.Id, +// "IP Address": device.IPAddress, +// "MAC Address": device.MACAddress, +// }).Debug("New Shelly Device not available anymore") +// } // Callen on RT connect func (c *ShellyClient) shellyClientLoop() { @@ -233,15 +235,13 @@ func (c *ShellyClient) shellyClientLoop() { // Run Client Loop to handle entity changes from device for { - select { - case msg := <-c.messages: - - switch msg { - case "disconnect": - return - } + msg := <-c.messages + switch msg { + case "disconnect": + return } + } } diff --git a/pkg/client/tasmotaclient.go b/pkg/client/tasmotaclient.go index 5ae5578..8f4d772 100644 --- a/pkg/client/tasmotaclient.go +++ b/pkg/client/tasmotaclient.go @@ -184,11 +184,11 @@ func (c *TasmotaClient) handleNewDeviceDiscovered(device *tasmota.TasmotaDevice) // Sonoff Basic switchEntity := entities.NewSwitchEntity(device.Topic, entities.LanguageText{En: "Tasmota " + device.FriendlyName[0]}, "") switchEntity.AddFeature(entities.OnOffSwitchEntityyFeatures) - switchEntity.AddFeature(entities.ToggleSwitchEntityCommand) + switchEntity.AddFeature(entities.ToggleSwitchEntityyFeatures) switchEntity.MapCommand(entities.OnSwitchEntityCommand, device.TurnOn) switchEntity.MapCommand(entities.OffSwitchEntityCommand, device.TurnOff) - switchEntity.MapCommand(entities.ToggleLightEntityCommand, device.Toggle) + switchEntity.MapCommand(entities.ToggleSwitchEntityCommand, device.Toggle) device.AddMsgReceivedFunc("RESULT", func(msg []byte) { @@ -238,18 +238,20 @@ func (c *TasmotaClient) handleNewDeviceDiscovered(device *tasmota.TasmotaDevice) } if tasmotaDevice != nil { - c.IntegrationDriver.AddEntity(tasmotaDevice) + if err := c.IntegrationDriver.AddEntity(tasmotaDevice); err != nil { + log.WithError(err).Error("Cannot add Entity") + } } } -func (c *TasmotaClient) handleRemoveDevice(device *tasmota.TasmotaDevice) { - log.WithFields(log.Fields{ - "Topic": device.Topic, - "IP Address": device.IPAddress, - "MAC Address": device.MACAddress, - }).Debug("Tasmota Device not available anymore") -} +// func (c *TasmotaClient) handleRemoveDevice(device *tasmota.TasmotaDevice) { +// log.WithFields(log.Fields{ +// "Topic": device.Topic, +// "IP Address": device.IPAddress, +// "MAC Address": device.MACAddress, +// }).Debug("Tasmota Device not available anymore") +// } // Callen on RT connect func (c *TasmotaClient) tasmotaClientLoop() { @@ -274,15 +276,13 @@ func (c *TasmotaClient) tasmotaClientLoop() { // Run Client Loop to handle entity changes from device for { - select { - case msg := <-c.messages: - - switch msg { - case "disconnect": - return - } + msg := <-c.messages + switch msg { + case "disconnect": + return } + } } diff --git a/pkg/cmd/deconz/deconz.go b/pkg/cmd/deconz/deconz.go index 99b173d..dbaf231 100644 --- a/pkg/cmd/deconz/deconz.go +++ b/pkg/cmd/deconz/deconz.go @@ -30,7 +30,9 @@ func NewCommand(rootCmd *cobra.Command) *cobra.Command { } var config integration.Config - viper.Unmarshal(&config) + if err := viper.Unmarshal(&config); err != nil { + log.WithError(err).Error("Cannot unmarshal config with viper") + } i, err := integration.NewIntegration(config) cmd.CheckError(err) diff --git a/pkg/cmd/denonavr/denonavr.go b/pkg/cmd/denonavr/denonavr.go index 640a6fa..219d094 100644 --- a/pkg/cmd/denonavr/denonavr.go +++ b/pkg/cmd/denonavr/denonavr.go @@ -30,7 +30,9 @@ func NewCommand(rootCmd *cobra.Command) *cobra.Command { } var config integration.Config - viper.Unmarshal(&config) + if err := viper.Unmarshal(&config); err != nil { + log.WithError(err).Error("Cannot unmarshal config with viper") + } i, err := integration.NewIntegration(config) cmd.CheckError(err) diff --git a/pkg/cmd/shelly/shelly.go b/pkg/cmd/shelly/shelly.go index 8d54f4b..5ebc833 100644 --- a/pkg/cmd/shelly/shelly.go +++ b/pkg/cmd/shelly/shelly.go @@ -30,7 +30,9 @@ func NewCommand(rootCmd *cobra.Command) *cobra.Command { } var config integration.Config - viper.Unmarshal(&config) + if err := viper.Unmarshal(&config); err != nil { + log.WithError(err).Error("Cannot unmarshal config with viper") + } i, err := integration.NewIntegration(config) cmd.CheckError(err) diff --git a/pkg/cmd/tasmota/tasmota.go b/pkg/cmd/tasmota/tasmota.go index 93647f6..44303c7 100644 --- a/pkg/cmd/tasmota/tasmota.go +++ b/pkg/cmd/tasmota/tasmota.go @@ -30,7 +30,9 @@ func NewCommand(rootCmd *cobra.Command) *cobra.Command { } var config integration.Config - viper.Unmarshal(&config) + if err := viper.Unmarshal(&config); err != nil { + log.WithError(err).Error("Cannot unmarshal config with viper") + } i, err := integration.NewIntegration(config) cmd.CheckError(err) diff --git a/pkg/cmd/ucrt/ucrt.go b/pkg/cmd/ucrt/ucrt.go index 7632acf..f6b2714 100644 --- a/pkg/cmd/ucrt/ucrt.go +++ b/pkg/cmd/ucrt/ucrt.go @@ -6,6 +6,8 @@ import ( "github.com/splattner/goucrt/pkg/cmd/deconz" "github.com/splattner/goucrt/pkg/cmd/denonavr" "github.com/splattner/goucrt/pkg/cmd/shelly" + + log "github.com/sirupsen/logrus" ) func NewCommand(name string) *cobra.Command { @@ -17,43 +19,81 @@ func NewCommand(name string) *cobra.Command { } rootCmd.PersistentFlags().IntP("listenPort", "l", 8080, "the port this integration is listening for websocket connection from the remote") - viper.BindPFlag("listenPort", rootCmd.PersistentFlags().Lookup("listenPort")) - viper.BindEnv("listenPort", "UC_INTEGRATION_LISTEN_PORT") + if err := viper.BindPFlag("listenPort", rootCmd.PersistentFlags().Lookup("listenPort")); err != nil { + log.WithError(err).Error(("Cannot bindPFplag")) + } + if err := viper.BindEnv("listenPort", "UC_INTEGRATION_LISTEN_PORT"); err != nil { + log.WithError(err).Error(("Cannot BindEnv")) + } rootCmd.PersistentFlags().String("websocketPath", "/ws", "path where this integration is available for websocket connections") - viper.BindPFlag("websocketPath", rootCmd.PersistentFlags().Lookup("websocketPath")) - viper.BindEnv("websocketPath", "UC_INTEGRATION_WEBSOCKET_PATH") + if err := viper.BindPFlag("websocketPath", rootCmd.PersistentFlags().Lookup("websocketPath")); err != nil { + log.WithError(err).Error(("Cannot bindPFplag")) + } + if err := viper.BindEnv("websocketPath", "UC_INTEGRATION_WEBSOCKET_PATH"); err != nil { + log.WithError(err).Error(("Cannot BindEnv")) + } rootCmd.PersistentFlags().Bool("disableMDNS", false, "Disable integration advertisement via mDNS") - viper.BindPFlag("disableMDNS", rootCmd.PersistentFlags().Lookup("disableMDNS")) - viper.BindEnv("disableMDNS", "UC_DISABLE_MDNS_PUBLISH") + if err := viper.BindPFlag("disableMDNS", rootCmd.PersistentFlags().Lookup("disableMDNS")); err != nil { + log.WithError(err).Error(("Cannot bindPFplag")) + } + if err := viper.BindEnv("disableMDNS", "UC_DISABLE_MDNS_PUBLISH"); err != nil { + log.WithError(err).Error(("Cannot BindEnv")) + } rootCmd.PersistentFlags().String("remoteTwoIP", "", "IP Address of your Remote Two instance (disables Remote Two discovery)") - viper.BindPFlag("remoteTwoIP", rootCmd.PersistentFlags().Lookup("remoteTwoIP")) - viper.BindEnv("remoteTwoIP", "UC_RT_HOST") + if err := viper.BindPFlag("remoteTwoIP", rootCmd.PersistentFlags().Lookup("remoteTwoIP")); err != nil { + log.WithError(err).Error(("Cannot bindPFplag")) + } + if err := viper.BindEnv("remoteTwoIP", "UC_RT_HOST"); err != nil { + log.WithError(err).Error(("Cannot BindEnv")) + } rootCmd.PersistentFlags().Int("remoteTwoPort", 80, "Port of your Remote Two instance (disables Remote Two discovery)") - viper.BindPFlag("remoteTwoPort", rootCmd.PersistentFlags().Lookup("remoteTwoPort")) - viper.BindEnv("remoteTwoPort", "UC_RT_PORT") + if err := viper.BindPFlag("remoteTwoPort", rootCmd.PersistentFlags().Lookup("remoteTwoPort")); err != nil { + log.WithError(err).Error(("Cannot bindPFplag")) + } + if err := viper.BindEnv("remoteTwoPort", "UC_RT_PORT"); err != nil { + log.WithError(err).Error(("Cannot BindEnv")) + } rootCmd.PersistentFlags().Bool("registration", false, "Enable driver registration on the Remote Two instead of mDNS advertisement") - viper.BindPFlag("registration", rootCmd.PersistentFlags().Lookup("registration")) - viper.BindEnv("registration", "UC_ENABLE_REGISTRATION") + if err := viper.BindPFlag("registration", rootCmd.PersistentFlags().Lookup("registration")); err != nil { + log.WithError(err).Error(("Cannot bindPFplag")) + } + if err := viper.BindEnv("registration", "UC_ENABLE_REGISTRATION"); err != nil { + log.WithError(err).Error(("Cannot BindEnv")) + } rootCmd.PersistentFlags().String("registrationUsername", "web-configurator", "Username of the RemoteTwo for driver registration") - viper.BindPFlag("registrationUsername", rootCmd.PersistentFlags().Lookup("registrationUsername")) - viper.BindEnv("registrationUsername", "UC_REGISTRATION_USERNAME") + if err := viper.BindPFlag("registrationUsername", rootCmd.PersistentFlags().Lookup("registrationUsername")); err != nil { + log.WithError(err).Error(("Cannot bindPFplag")) + } + if err := viper.BindEnv("registrationUsername", "UC_REGISTRATION_USERNAME"); err != nil { + log.WithError(err).Error(("Cannot BindEnv")) + } rootCmd.PersistentFlags().String("registrationPin", "", "Pin of the RemoteTwo for driver registration") - viper.BindPFlag("registrationPin", rootCmd.PersistentFlags().Lookup("registrationPin")) - viper.BindEnv("registrationUsername", "UC_REGISTRATION_PIN") + if err := viper.BindPFlag("registrationPin", rootCmd.PersistentFlags().Lookup("registrationPin")); err != nil { + log.WithError(err).Error(("Cannot bindPFplag")) + } + if err := viper.BindEnv("registrationUsername", "UC_REGISTRATION_PIN"); err != nil { + log.WithError(err).Error(("Cannot BindEnv")) + } rootCmd.PersistentFlags().Bool("debug", false, "Enable debug log level") - viper.BindPFlag("debug", rootCmd.PersistentFlags().Lookup("debug")) + if err := viper.BindPFlag("debug", rootCmd.PersistentFlags().Lookup("debug")); err != nil { + log.WithError(err).Error(("Cannot bindPFplag")) + } rootCmd.PersistentFlags().String("ucconfighome", "./ucconfig/", "Configuration directory to save the user configuration from the driver setup") - viper.BindPFlag("ucconfighome", rootCmd.PersistentFlags().Lookup("ucconfighome")) - viper.BindEnv("ucconfighome", "UC_CONFIG_HOME") + if err := viper.BindPFlag("ucconfighome", rootCmd.PersistentFlags().Lookup("ucconfighome")); err != nil { + log.WithError(err).Error(("Cannot bindPFplag")) + } + if err := viper.BindEnv("ucconfighome", "UC_CONFIG_HOME"); err != nil { + log.WithError(err).Error(("Cannot BindEnv")) + } rootCmd.AddCommand( denonavr.NewCommand(rootCmd), diff --git a/pkg/deconz/device.go b/pkg/deconz/device.go index 02fb554..e6b07d3 100644 --- a/pkg/deconz/device.go +++ b/pkg/deconz/device.go @@ -8,8 +8,8 @@ type DeconzDeviceType string const ( LightDeconzDeviceType DeconzDeviceType = "light" - GroupDeconzDeviceType = "group" - SensorDeconzDeviceType = "sensor" + GroupDeconzDeviceType DeconzDeviceType = "group" + SensorDeconzDeviceType DeconzDeviceType = "sensor" ) type DeconzDevice struct { @@ -122,12 +122,10 @@ func (d *DeconzDevice) TurnOff() error { func (d *DeconzDevice) Toggle() error { if d.IsOn() { - d.TurnOff() - } else { - d.TurnOn() + return d.TurnOff() } - return d.setState() + return d.TurnOn() } func (d *DeconzDevice) IsOn() bool { diff --git a/pkg/deconz/group.go b/pkg/deconz/group.go index 548424b..a2f890d 100644 --- a/pkg/deconz/group.go +++ b/pkg/deconz/group.go @@ -40,18 +40,26 @@ type DeconzGroup struct { func (d *Deconz) GetAllGroups() ([]DeconzGroup, error) { url := fmt.Sprintf(getAllGroupsURL, fmt.Sprintf("%s:%d", d.host, d.port), d.apikey) request, err := http.NewRequest("GET", url, nil) + if err != nil { + log.WithError(err).Error("Cannot create new http Request") + return nil, err + } client := http.Client{} response, err := client.Do(request) if err != nil { + log.WithError(err).Error("Cannot Do the request") return nil, err } defer response.Body.Close() contents, err := io.ReadAll(response.Body) if err != nil { + log.WithError(err).Error("Cannot Read the response body") return nil, err } groupsMap := map[string]DeconzGroup{} - json.Unmarshal(contents, &groupsMap) + if err := json.Unmarshal(contents, &groupsMap); err != nil { + log.WithError(err).Error("Cannon unmarshall data into map[string]DeconzGroup") + } groups := make([]DeconzGroup, 0, len(groupsMap)) for groupID, group := range groupsMap { group.TID = groupID @@ -134,7 +142,9 @@ func (d *DeconzDevice) SetGroupAttrs() ([]ApiResponse, error) { if err != nil { return apiResponse, err } - json.Unmarshal(contents, &apiResponse) + if err := json.Unmarshal(contents, &apiResponse); err != nil { + log.WithError(err).Error("Cannon unmarshall data into []ApiResponse") + } return apiResponse, err } diff --git a/pkg/deconz/types.go b/pkg/deconz/types.go index 2a240ab..94a8904 100644 --- a/pkg/deconz/types.go +++ b/pkg/deconz/types.go @@ -70,7 +70,7 @@ func (state *DeconzState) SetCT(Bri int, CT int) { } func (state *DeconzState) SetXY(x, y float32) { - state.XY = make([]float32, 2, 2) + state.XY = make([]float32, 2) state.XY[0] = x state.XY[1] = y } diff --git a/pkg/deconz/websocket.go b/pkg/deconz/websocket.go index 5c77068..1bc99ea 100644 --- a/pkg/deconz/websocket.go +++ b/pkg/deconz/websocket.go @@ -67,7 +67,9 @@ func (d *Deconz) StartandListenLoop() { return case <-ticker.C: - ws.SetWriteDeadline(time.Now().Add(writeWait)) + if err := ws.SetWriteDeadline(time.Now().Add(writeWait)); err != nil { + log.WithError(err).Error("Cannot Set write deadline on websocket") + } log.WithField("RemoteAddr", ws.RemoteAddr().String()).Debug("Deconz, Send Ping Message") if err := ws.WriteMessage(websocket.PingMessage, nil); err != nil { log.WithField("RemoteAddr", ws.RemoteAddr().String()).Info("Could not send Ping message") @@ -83,9 +85,13 @@ func (d *Deconz) websocketReceiveHandler(ws *websocket.Conn) { log.Info("Deconz, Starting Deconz Websocket receive handler") ws.SetReadLimit(maxMessageSize) - ws.SetReadDeadline(time.Now().Add(pongWait)) + if err := ws.SetReadDeadline(time.Now().Add(pongWait)); err != nil { + log.WithError(err).Error("Cannot Set read deadline on websocket") + } ws.SetPongHandler(func(string) error { - ws.SetReadDeadline(time.Now().Add(pongWait)) + if err := ws.SetReadDeadline(time.Now().Add(pongWait)); err != nil { + log.WithError(err).Error("Cannot Set read deadline on websocket") + } return nil }) diff --git a/pkg/denonavr/cursor.go b/pkg/denonavr/cursor.go index 5d810cc..de54c1d 100644 --- a/pkg/denonavr/cursor.go +++ b/pkg/denonavr/cursor.go @@ -4,11 +4,11 @@ type DenonCursorControl string const ( DenonCursorControlUp DenonCursorControl = "CUP" - DenonCursorControlDown = "CDN" - DenonCursorControlLeft = "CLT" - DenonCursorControlRight = "CRT" - DenonCursorControlEnter = "ENT" - DenonCursorControlReturn = "RTN" + DenonCursorControlDown DenonCursorControl = "CDN" + DenonCursorControlLeft DenonCursorControl = "CLT" + DenonCursorControlRight DenonCursorControl = "CRT" + DenonCursorControlEnter DenonCursorControl = "ENT" + DenonCursorControlReturn DenonCursorControl = "RTN" ) func (d *DenonAVR) CursorControl(cursorControl DenonCursorControl) int { diff --git a/pkg/denonavr/denonavr.go b/pkg/denonavr/denonavr.go index 92966bc..87badde 100644 --- a/pkg/denonavr/denonavr.go +++ b/pkg/denonavr/denonavr.go @@ -17,29 +17,29 @@ type DenonZone string const ( DenonCommandPower DenonCommand = "PW" - DennonCommandZoneMain = "ZM" - DenonCommandVolume = "MV" - DenonCommandMute = "MU" - DenonCommandSelectInput = "SI" - DenonCommandCursorControl = "MN" - DenonCommandNS = "NS" - DenonCommandMS = "MS" - DenonCommandVS = "VS" + DennonCommandZoneMain DenonCommand = "ZM" + DenonCommandVolume DenonCommand = "MV" + DenonCommandMute DenonCommand = "MU" + DenonCommandSelectInput DenonCommand = "SI" + DenonCommandCursorControl DenonCommand = "MN" + DenonCommandNS DenonCommand = "NS" + DenonCommandMS DenonCommand = "MS" + DenonCommandVS DenonCommand = "VS" DenonVolumeStep float64 = 1 ) const ( MainZone DenonZone = "MAIN" - Zone2 = "Z2" - Zone3 = "Z3" + Zone2 DenonZone = "Z2" + Zone3 DenonZone = "Z3" ) const ( STATUS_URL string = "/goform/formMainZone_MainZoneXmlStatus.xml" - STATUS_Z2_URL = "/goform/formZone2_Zone2XmlStatus.xml" - STATUS_Z3_URL = "/goform/formZone3_Zone3XmlStatus.xml" - MAINZONE_URL = "/goform/formMainZone_MainZoneXml.xml" - COMMAND_URL = "/goform/formiPhoneAppDirect.xml" + STATUS_Z2_URL string = "/goform/formZone2_Zone2XmlStatus.xml" + STATUS_Z3_URL string = "/goform/formZone3_Zone3XmlStatus.xml" + MAINZONE_URL string = "/goform/formMainZone_MainZoneXml.xml" + COMMAND_URL string = "/goform/formiPhoneAppDirect.xml" ) type DenonXML struct { @@ -122,6 +122,9 @@ func (d *DenonAVR) getMainZoneDataFromDevice() { } body, err := io.ReadAll(resp.Body) + if err != nil { + log.WithError(err).Error("Cannot read response body") + } if err := xml.Unmarshal(body, &d.mainZoneData); err != nil { log.WithError(err).Info("Could not unmarshall") diff --git a/pkg/denonavr/power.go b/pkg/denonavr/power.go index beb5734..206b55f 100644 --- a/pkg/denonavr/power.go +++ b/pkg/denonavr/power.go @@ -1,14 +1,19 @@ package denonavr func (d *DenonAVR) TurnOn() error { - d.sendCommandToDevice(DenonCommandPower, "ON") + if _, err := d.sendCommandToDevice(DenonCommandPower, "ON"); err != nil { + return err + } _, err := d.sendCommandToDevice(DennonCommandZoneMain, "ON") return err } func (d *DenonAVR) TurnOff() error { - d.sendCommandToDevice(DenonCommandPower, "STANDBY") + + if _, err := d.sendCommandToDevice(DenonCommandPower, "STANDBY"); err != nil { + return err + } _, err := d.sendCommandToDevice(DennonCommandZoneMain, "OFF") return err diff --git a/pkg/denonavr/status.go b/pkg/denonavr/status.go index 8730542..ee1b8b1 100644 --- a/pkg/denonavr/status.go +++ b/pkg/denonavr/status.go @@ -51,6 +51,9 @@ func (d *DenonAVR) getZoneStatusFromDevice(url string) DenonStatus { } body, err := io.ReadAll(resp.Body) + if err != nil { + log.WithError(err).Error("Cannot read response body") + } if err := xml.Unmarshal(body, &status); err != nil { log.WithError(err).Info("Could not unmarshall") diff --git a/pkg/entities/climate.go b/pkg/entities/climate.go index fec6d61..87bd654 100644 --- a/pkg/entities/climate.go +++ b/pkg/entities/climate.go @@ -7,39 +7,39 @@ type ClimateEntityCommand string const ( OffClimateEntityState ClimateEntityState = "OFF" - HeatClimateEntityState = "HEAT" - CoolClimateEntityState = "Cool" - HeatCoolClimateEntityState = "HEAT_COOL" - FanClimateEntityState = "FAN" - AutoClimateEntityState = "Auto" + HeatClimateEntityState ClimateEntityState = "HEAT" + CoolClimateEntityState ClimateEntityState = "Cool" + HeatCoolClimateEntityState ClimateEntityState = "HEAT_COOL" + FanClimateEntityState ClimateEntityState = "FAN" + AutoClimateEntityStat ClimateEntityState = "Auto" ) const ( OnOffClimateEntityFeatures ClimateEntityFeatures = "on_off" - HeatClimateEntityFeatures = "heat" - CoolClimateEntityFeatures = "cool" - CurrentTemperatureClimateEntityFeatures = "current_temperature" - TargetTemperaturClimateEntityFeatures = "target_temperatur" - TargetTemperaturRangeClimateEntityFeatures = "target_temperature_range" - FanClimateEntityFeatures = "fan" + HeatClimateEntityFeatures ClimateEntityFeatures = "heat" + CoolClimateEntityFeatures ClimateEntityFeatures = "cool" + CurrentTemperatureClimateEntityFeatures ClimateEntityFeatures = "current_temperature" + TargetTemperaturClimateEntityFeatures ClimateEntityFeatures = "target_temperatur" + TargetTemperaturRangeClimateEntityFeatures ClimateEntityFeatures = "target_temperature_range" + FanClimateEntityFeatures ClimateEntityFeatures = "fan" ) const ( OnClimateEntityCommand ClimateEntityCommand = "on" - OffClimateEntityCommand = "off" - HVACModeClimateEntityCommand = "hvac_mode" - TargetTemperatureClimateEntityCommand = "target_temperature" - TargetTemperatureRangeClimateEntityCommand = "target_temperature_range" - FanModeClimateEntityCommand = "fan_mode" + OffClimateEntityCommand ClimateEntityCommand = "off" + HVACModeClimateEntityCommand ClimateEntityCommand = "hvac_mode" + TargetTemperatureClimateEntityCommand ClimateEntityCommand = "target_temperature" + TargetTemperatureRangeClimateEntityCommand ClimateEntityCommand = "target_temperature_range" + FanModeClimateEntityCommand ClimateEntityCommand = "fan_mode" ) const ( StateClimateEntityAttribute ClimateEntityAttributes = "state" - CurrentTemperatureClimateEntityAttribute = "current_temperature" - TargetTemperatureClimateEntityAttribute = "target_temperature" - TargetTemperatureHighClimateEntityAttribute = "target_temperature_high" - TargetTemperatureLowClimateEntityAttribute = "target_temperature_low" - FanModeClimateEntityAttribute = " fan_mode" + CurrentTemperatureClimateEntityAttribute ClimateEntityAttributes = "current_temperature" + TargetTemperatureClimateEntityAttribute ClimateEntityAttributes = "target_temperature" + TargetTemperatureHighClimateEntityAttribute ClimateEntityAttributes = "target_temperature_high" + TargetTemperatureLowClimateEntityAttribute ClimateEntityAttributes = "target_temperature_low" + FanModeClimateEntityAttribute ClimateEntityAttributes = " fan_mode" ) type ClimateEntity struct { diff --git a/pkg/entities/cover.go b/pkg/entities/cover.go index c407475..8537b84 100644 --- a/pkg/entities/cover.go +++ b/pkg/entities/cover.go @@ -7,36 +7,36 @@ type CoverEntityCommand string const ( OpeningCoverEntityState CoverEntityState = "OPENING" - OpenCoverEntityState = "OPEN" - ClosingCoverEntityState = "CLOSING" - CloseCoverEntityState = "CLOSED" + OpenCoverEntityState CoverEntityState = "OPEN" + ClosingCoverEntityState CoverEntityState = "CLOSING" + CloseCoverEntityState CoverEntityState = "CLOSED" ) const ( OpenCoverEntityFeatures CoverEntityFeatures = "open" - CloseCoverEntityFeatures = "close" - StopCoverEntityFeatures = "stop" - PositionCoverEntityFeatures = "position" - TiltCoverEntityFeatures = "tilt" - TiltStopCoverEntityFeatures = "tilt_stop" - TiltPositionCoverEntityFeatures = "tilt_position" + CloseCoverEntityFeatures CoverEntityFeatures = "close" + StopCoverEntityFeatures CoverEntityFeatures = "stop" + PositionCoverEntityFeatures CoverEntityFeatures = "position" + TiltCoverEntityFeatures CoverEntityFeatures = "tilt" + TiltStopCoverEntityFeatures CoverEntityFeatures = "tilt_stop" + TiltPositionCoverEntityFeatures CoverEntityFeatures = "tilt_position" ) const ( OpenCoverEntityCommand CoverEntityCommand = "open" - CloseCoverEntityCommand = "close" - StopCoverEntityyommand = "stop" - PositionCoverEntityCommand = "position" - TiltCoverEntityCommand = "tilt" - TiltUpCoverEntityCommand = "tilt_up" - TiltDownCoverEntityCommand = "tilt_down" - TiltStopCoverEntityCommand = "tilt_stop" + CloseCoverEntityCommand CoverEntityCommand = "close" + StopCoverEntityyommand CoverEntityCommand = "stop" + PositionCoverEntityCommand CoverEntityCommand = "position" + TiltCoverEntityCommand CoverEntityCommand = "tilt" + TiltUpCoverEntityCommand CoverEntityCommand = "tilt_up" + TiltDownCoverEntityCommand CoverEntityCommand = "tilt_down" + TiltStopCoverEntityCommand CoverEntityCommand = "tilt_stop" ) const ( StateCoverEntityAttribute CoverEntityAttributes = "state" - PositionCoverEntityAttribute = "position" - TiltPositionCoverEntityAttribute = "tilt_position" + PositionCoverEntityAttribute CoverEntityAttributes = "position" + TiltPositionCoverEntityAttribute CoverEntityAttributes = "tilt_position" ) type CoverEntity struct { diff --git a/pkg/entities/entities.go b/pkg/entities/entities.go index df90b17..423a114 100644 --- a/pkg/entities/entities.go +++ b/pkg/entities/entities.go @@ -8,7 +8,7 @@ type EntityState string const ( UnavailableEntityState EntityState = "UNAVAILABLE" - UnkownEntityState = "UNKNOWN" + UnkownEntityState EntityState = "UNKNOWN" ) // Generic Remote Two Entity diff --git a/pkg/entities/light.go b/pkg/entities/light.go index 5c5208f..34432c7 100644 --- a/pkg/entities/light.go +++ b/pkg/entities/light.go @@ -11,31 +11,31 @@ type LightEntityCommand string const ( OnLightEntityState LightEntityState = "ON" - OffLightEntityState = "OFF" - UnavailableLightEntityState = "UNAVAILABLE" - UnknownLightEntityState = "UNKNOWN" + OffLightEntityState LightEntityState = "OFF" + UnavailableLightEntityState LightEntityState = "UNAVAILABLE" + UnknownLightEntityState LightEntityState = "UNKNOWN" ) const ( OnOffLightEntityFeatures LightEntityFeatures = "on_off" - ToggleLightEntityFeatures = "toggle" - DimLightEntityFeatures = "dim" - ColorLightEntityFeatures = "color" - ColorTemperatureLightEntityFeatures = "color_temperature" + ToggleLightEntityFeatures LightEntityFeatures = "toggle" + DimLightEntityFeatures LightEntityFeatures = "dim" + ColorLightEntityFeatures LightEntityFeatures = "color" + ColorTemperatureLightEntityFeatures LightEntityFeatures = "color_temperature" ) const ( OnLightEntityCommand LightEntityCommand = "on" - OffLightEntityCommand = "off" - ToggleLightEntityCommand = "toggle" + OffLightEntityCommand LightEntityCommand = "off" + ToggleLightEntityCommand LightEntityCommand = "toggle" ) const ( StateLightEntityAttribute LightEntityAttributes = "state" - HueLightEntityAttribute = "hue" - SaturationLightEntityAttribute = "saturation" - BrightnessLightEntityAttribute = "brightness" - ColorTemperatureLightEntityAttribute = "color_temperature" + HueLightEntityAttribute LightEntityAttributes = "hue" + SaturationLightEntityAttribute LightEntityAttributes = "saturation" + BrightnessLightEntityAttribute LightEntityAttributes = "brightness" + ColorTemperatureLightEntityAttribute LightEntityAttributes = "color_temperature" ) type LightEntity struct { diff --git a/pkg/entities/media_player.go b/pkg/entities/media_player.go index ba9b083..3de5ba5 100644 --- a/pkg/entities/media_player.go +++ b/pkg/entities/media_player.go @@ -8,109 +8,109 @@ type MediaPlayerDeviceClass string const ( OnMediaPlayerEntityState MediaPlayerEntityState = "ON" - OffMediaPlayerEntityState = "OFF" - PlayingPlayerEntityState = "PLAYING" - PausedMediaPlayerEntityState = "PAUSED" - StandbyMediaPlayerEntityState = "STANDBY" - BufferingMediaPlayerEntityState = "BUFFERING" + OffMediaPlayerEntityState MediaPlayerEntityState = "OFF" + PlayingPlayerEntityState MediaPlayerEntityState = "PLAYING" + PausedMediaPlayerEntityState MediaPlayerEntityState = "PAUSED" + StandbyMediaPlayerEntityState MediaPlayerEntityState = "STANDBY" + BufferingMediaPlayerEntityState MediaPlayerEntityState = "BUFFERING" ) const ( OnOffMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "on_off" - ToggleMediaPlayerEntityyFeatures = "toggle" - VolumeMediaPlayerEntityyFeatures = "volume" - VolumeUpDownMediaPlayerEntityFeatures = "volume_up_down" - MuteToggleMediaPlayerEntityFeatures = "mute_toggle" - MuteMediaPlayerEntityFeatures = "mute" - UnmuteMediaPlayerEntityFeatures = "unmtue" - PlayPauseMediaPlayerEntityFeatures = "play_pause" - StopMediaPlayerEntityFeatures = "stop" - NextMediaPlayerEntityFeatures = "next" - PreviusMediaPlayerEntityFeatures = "previous" - FastForwardMediaPlayerEntityFeatures = "fast_forward" - RewindMediaPlayerEntityFeatures = "rewind" - RepeatMediaPlayerEntityFeatures = "repeat" - ShuffleMediaPlayerEntityFeatures = "shuffle" - SeekMediaPlayerEntityFeatures = "seek" - MediaDurationMediaPlayerEntityFeatures = "media_duration" - MediaPositionMediaPlayerEntityFeatures = "media_position" - MediaTitleMediaPlayerEntityFeatures = "media_title" - MediaArtistMediaPlayerEntityFeatures = "media_artist" - MediaAlbumMediaPlayerEntityFeatures = "media_album" - MediaImageUrlMediaPlayerEntityFeatures = "media_image_url" - MediaTypeMediaPlayerEntityFeatures = "media_type" - DPadMediaPlayerEntityFeatures = "dpad" - HomeMediaPlayerEntityFeatures = "home" - MenuMediaPlayerEntityFeatures = "menu" - ColorButtonsMediaPlayerEntityFeatures = "color_buttons" - ChannelSwitcherMediaPlayerEntityFeatures = "channel_switcher" - SelectSourceMediaPlayerEntityFeatures = "select_source" - SelectSoundModeMediaPlayerEntityFeatures = "select_sound_mode" + ToggleMediaPlayerEntityyFeatures MediaPlayerEntityFeatures = "toggle" + VolumeMediaPlayerEntityyFeatures MediaPlayerEntityFeatures = "volume" + VolumeUpDownMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "volume_up_down" + MuteToggleMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "mute_toggle" + MuteMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "mute" + UnmuteMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "unmtue" + PlayPauseMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "play_pause" + StopMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "stop" + NextMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "next" + PreviusMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "previous" + FastForwardMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "fast_forward" + RewindMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "rewind" + RepeatMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "repeat" + ShuffleMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "shuffle" + SeekMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "seek" + MediaDurationMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "media_duration" + MediaPositionMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "media_position" + MediaTitleMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "media_title" + MediaArtistMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "media_artist" + MediaAlbumMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "media_album" + MediaImageUrlMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "media_image_url" + MediaTypeMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "media_type" + DPadMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "dpad" + HomeMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "home" + MenuMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "menu" + ColorButtonsMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "color_buttons" + ChannelSwitcherMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "channel_switcher" + SelectSourceMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "select_source" + SelectSoundModeMediaPlayerEntityFeatures MediaPlayerEntityFeatures = "select_sound_mode" ) const ( StateMediaPlayerEntityAttribute MediaPlayerEntityAttributes = "state" - VolumeMediaPlayerEntityAttribute = "volume" - MutedMediaPlayeEntityAttribute = "muted" - MediaDurationMediaPlayerEntityAttribute = "media_duration" - MediaPositionMediaPlayerEntityAttribute = "media_position" - MediaTypeMediaPlayerEntityAttribute = "media_type" - MediaImageUrlMediaPlayerEntityAttribute = "media_image_url" - MediaTitleMediaPlayerEntityAttribute = "media_title" - MediaArtistMediaPlayerEntityAttribute = "media_artist" - MediaAlbumMediaPlayerEntityAttribute = "media_album" - RepeatMediaPlayerEntityAttribute = "repeat" - ShuffleMediaPlayerEntityAttribute = "shuffle" - SourceMediaPlayerEntityAttribute = "source" - SourceListMediaPlayerEntityAttribute = "source_list" - SoundModeMediaPlayerEntityAttribute = "sound_mode" - SoundModeListMediaPlayerEntityAttribute = "sound_mode_list" + VolumeMediaPlayerEntityAttribute MediaPlayerEntityAttributes = "volume" + MutedMediaPlayeEntityAttribute MediaPlayerEntityAttributes = "muted" + MediaDurationMediaPlayerEntityAttribute MediaPlayerEntityAttributes = "media_duration" + MediaPositionMediaPlayerEntityAttribute MediaPlayerEntityAttributes = "media_position" + MediaTypeMediaPlayerEntityAttribute MediaPlayerEntityAttributes = "media_type" + MediaImageUrlMediaPlayerEntityAttribute MediaPlayerEntityAttributes = "media_image_url" + MediaTitleMediaPlayerEntityAttribute MediaPlayerEntityAttributes = "media_title" + MediaArtistMediaPlayerEntityAttribute MediaPlayerEntityAttributes = "media_artist" + MediaAlbumMediaPlayerEntityAttribute MediaPlayerEntityAttributes = "media_album" + RepeatMediaPlayerEntityAttribute MediaPlayerEntityAttributes = "repeat" + ShuffleMediaPlayerEntityAttribute MediaPlayerEntityAttributes = "shuffle" + SourceMediaPlayerEntityAttribute MediaPlayerEntityAttributes = "source" + SourceListMediaPlayerEntityAttribute MediaPlayerEntityAttributes = "source_list" + SoundModeMediaPlayerEntityAttribute MediaPlayerEntityAttributes = "sound_mode" + SoundModeListMediaPlayerEntityAttribute MediaPlayerEntityAttributes = "sound_mode_list" ) const ( OnMediaPlayerEntityCommand MediaPlayerEntityCommand = "on" - OffMediaPlayerEntityCommand = "off" - ToggleMediaPlayerEntityCommand = "toggle" - PlayPauseMediaPlayerEntityCommand = "play_pause" - StopMediaPlayerEntityCommand = "stop" - PreviusMediaPlayerEntityCommand = "previous" - NextMediaPlayerEntityCommand = "next" - FastForwardMediaPlayerEntityCommand = "fast_forward" - RewindMediaPlayerEntityCommand = "rewind" - SeekMediaPlayerEntityCommand = "seek" - VolumeMediaPlayerEntityCommand = "volume" - VolumeUpMediaPlayerEntityCommand = "volume_up" - VolumeDownMediaPlayerEntityCommand = "volume_down" - MuteToggleMediaPlayerEntityCommand = "mute_toggle" - MuteMediaPlayerEntityCommand = "mute" - UnmuteMediaPlayerEntityCommand = "unmute" - RepeatMediaPlayerEntityCommand = "repeat" - ShuffleMediaPlayerEntityCommand = "shuffle" - ChannelUpMediaPlayerEntityCommand = "channel_up" - ChannelDownMediaPlayerEntityCommand = "channel_down" - CursorUpMediaPlayerEntityCommand = "cursor_up" - CursorDownMediaPlayerEntityCommand = "cursor_down" - CursorLeftMediaPlayerEntityCommand = "cursor_left" - CursorRightMediaPlayerEntityCommand = "cursor_right" - CursorEnterMediaPlayerEntityCommand = "cursor_enter" - FunctionRedMediaPlayerEntityCommand = "function_red" - FunctionGreenMediaPlayerEntityCommand = "function_green" - FunctionYellowMediaPlayerEntityCommand = "function_yellow" - FunctionBlueMediaPlayerEntityCommand = "function_blue" - HomeMediaPlayerEntityCommand = "home" - MenuMediaPlayerEntityCommand = "menu" - BackMediaPlayerEntityCommand = "back" - SelectSourcMediaPlayerEntityCommand = "select_source" - SelectSoundModeMediaPlayerEntityCommand = "select_sound_mode" - SearchMediaPlayerEntityCommand = "search" + OffMediaPlayerEntityCommand MediaPlayerEntityCommand = "off" + ToggleMediaPlayerEntityCommand MediaPlayerEntityCommand = "toggle" + PlayPauseMediaPlayerEntityCommand MediaPlayerEntityCommand = "play_pause" + StopMediaPlayerEntityCommand MediaPlayerEntityCommand = "stop" + PreviusMediaPlayerEntityCommand MediaPlayerEntityCommand = "previous" + NextMediaPlayerEntityCommand MediaPlayerEntityCommand = "next" + FastForwardMediaPlayerEntityCommand MediaPlayerEntityCommand = "fast_forward" + RewindMediaPlayerEntityCommand MediaPlayerEntityCommand = "rewind" + SeekMediaPlayerEntityCommand MediaPlayerEntityCommand = "seek" + VolumeMediaPlayerEntityCommand MediaPlayerEntityCommand = "volume" + VolumeUpMediaPlayerEntityCommand MediaPlayerEntityCommand = "volume_up" + VolumeDownMediaPlayerEntityCommand MediaPlayerEntityCommand = "volume_down" + MuteToggleMediaPlayerEntityCommand MediaPlayerEntityCommand = "mute_toggle" + MuteMediaPlayerEntityCommand MediaPlayerEntityCommand = "mute" + UnmuteMediaPlayerEntityCommand MediaPlayerEntityCommand = "unmute" + RepeatMediaPlayerEntityCommand MediaPlayerEntityCommand = "repeat" + ShuffleMediaPlayerEntityCommand MediaPlayerEntityCommand = "shuffle" + ChannelUpMediaPlayerEntityCommand MediaPlayerEntityCommand = "channel_up" + ChannelDownMediaPlayerEntityCommand MediaPlayerEntityCommand = "channel_down" + CursorUpMediaPlayerEntityCommand MediaPlayerEntityCommand = "cursor_up" + CursorDownMediaPlayerEntityCommand MediaPlayerEntityCommand = "cursor_down" + CursorLeftMediaPlayerEntityCommand MediaPlayerEntityCommand = "cursor_left" + CursorRightMediaPlayerEntityCommand MediaPlayerEntityCommand = "cursor_right" + CursorEnterMediaPlayerEntityCommand MediaPlayerEntityCommand = "cursor_enter" + FunctionRedMediaPlayerEntityCommand MediaPlayerEntityCommand = "function_red" + FunctionGreenMediaPlayerEntityCommand MediaPlayerEntityCommand = "function_green" + FunctionYellowMediaPlayerEntityCommand MediaPlayerEntityCommand = "function_yellow" + FunctionBlueMediaPlayerEntityCommand MediaPlayerEntityCommand = "function_blue" + HomeMediaPlayerEntityCommand MediaPlayerEntityCommand = "home" + MenuMediaPlayerEntityCommand MediaPlayerEntityCommand = "menu" + BackMediaPlayerEntityCommand MediaPlayerEntityCommand = "back" + SelectSourcMediaPlayerEntityCommand MediaPlayerEntityCommand = "select_source" + SelectSoundModeMediaPlayerEntityCommand MediaPlayerEntityCommand = "select_sound_mode" + SearchMediaPlayerEntityCommand MediaPlayerEntityCommand = "search" ) const ( ReceiverMediaPlayerDeviceClass MediaPlayerDeviceClass = "receiver" - SetTopBoxMediaPlayerDeviceClass = "set_top_box" - SpeakerMediaPlayerDeviceClass = "speaker" - StreamingBoxMMediaPlayerDeviceClass = "streaming_box" - TVMediaPlayerDeviceClass = "tv" + SetTopBoxMediaPlayerDeviceClass MediaPlayerDeviceClass = "set_top_box" + SpeakerMediaPlayerDeviceClass MediaPlayerDeviceClass = "speaker" + StreamingBoxMMediaPlayerDeviceClass MediaPlayerDeviceClass = "streaming_box" + TVMediaPlayerDeviceClass MediaPlayerDeviceClass = "tv" ) type MediaPlayerEntity struct { diff --git a/pkg/entities/sensor.go b/pkg/entities/sensor.go index 23b2965..e90decc 100644 --- a/pkg/entities/sensor.go +++ b/pkg/entities/sensor.go @@ -12,19 +12,19 @@ const ( const ( StateSensorEntityyAttribute SensorEntityAttributes = "state" - ValueSensortEntityyAttribute = "value" - UnitSSensorntityyAttribute = "unit" + ValueSensortEntityyAttribute SensorEntityAttributes = "value" + UnitSSensorntityyAttribute SensorEntityAttributes = "unit" ) const ( CustomSensorDeviceClass SensorDeviceClass = "custom" - BatterySensorDeviceClass = "battery" - CurrentSensorDeviceClass = "current" - EnegrySensorDeviceClass = "energy" - HumiditySensorDeviceClass = "humidity" - PowerSensorDeviceClass = "power" - TemperaturSensorDeviceClass = "temperatur" - VoltageSensorDeviceClass = "voltage" + BatterySensorDeviceClass SensorDeviceClass = "battery" + CurrentSensorDeviceClass SensorDeviceClass = "current" + EnegrySensorDeviceClass SensorDeviceClass = "energy" + HumiditySensorDeviceClass SensorDeviceClass = "humidity" + PowerSensorDeviceClass SensorDeviceClass = "power" + TemperaturSensorDeviceClass SensorDeviceClass = "temperatur" + VoltageSensorDeviceClass SensorDeviceClass = "voltage" ) type SensorEntity struct { diff --git a/pkg/entities/switch.go b/pkg/entities/switch.go index c77b1cd..2a12a5d 100644 --- a/pkg/entities/switch.go +++ b/pkg/entities/switch.go @@ -7,12 +7,12 @@ type SwitchEntityCommand string const ( OnSwitchtEntityState SwitchEntityState = "ON" - OffSwitchtEntityState = "OFF" + OffSwitchtEntityState SwitchEntityState = "OFF" ) const ( OnOffSwitchEntityyFeatures SwitchEntityFeatures = "on_off" - ToggleSwitchEntityyFeatures = "toggle" + ToggleSwitchEntityyFeatures SwitchEntityFeatures = "toggle" ) const ( @@ -21,8 +21,8 @@ const ( const ( OnSwitchEntityCommand SwitchEntityCommand = "on" - OffSwitchEntityCommand = "off" - ToggleSwitchEntityCommand = "toggle" + OffSwitchEntityCommand SwitchEntityCommand = "off" + ToggleSwitchEntityCommand SwitchEntityCommand = "toggle" ) type SwitchsEntity struct { diff --git a/pkg/integration/device.go b/pkg/integration/device.go index 7399c19..5d5d184 100644 --- a/pkg/integration/device.go +++ b/pkg/integration/device.go @@ -8,9 +8,9 @@ type DState string const ( ConnectedDeviceState DState = "CONNECTED" - ConnectingDeviceState = "CONNECTING" - DisconnectedDeviceState = "DISCONNECTED" - ErrorDeviceState = "ERROR" + ConnectingDeviceState DState = "CONNECTING" + DisconnectedDeviceState DState = "DISCONNECTED" + ErrorDeviceState DState = "ERROR" ) func (i *Integration) SetDeviceState(state DState) { diff --git a/pkg/integration/events.go b/pkg/integration/events.go index c4d2c37..e5c547d 100644 --- a/pkg/integration/events.go +++ b/pkg/integration/events.go @@ -16,7 +16,10 @@ func (i *Integration) sendEventMessage(res *interface{}, messageType int) error // Unmarshal againinto Event Message for some fields event := EventMessage{} - json.Unmarshal(msg, &event) + if err := json.Unmarshal(msg, &event); err != nil { + log.WithError(err).Error("Cannot unmarshal Event Message") + return err + } if i.Remote.standby { log.WithFields(log.Fields{ @@ -59,20 +62,29 @@ func (i *Integration) handleEvent(req *RequestMessage, p []byte) interface{} { case "connect": connectEvent := ConnectEvent{} - json.Unmarshal(p, &connectEvent) + if err := json.Unmarshal(p, &connectEvent); err != nil { + log.WithError(err).Error("Cannot unmarshal ConnectEvent") + return nil + } i.handleConnectEvent(&connectEvent) case "disconnect": connectEvent := ConnectEvent{} - json.Unmarshal(p, &connectEvent) - + if err := json.Unmarshal(p, &connectEvent); err != nil { + log.WithError(err).Error("Cannot unmarshal ConnectEvent") + return nil + } i.handleConnectEvent(&connectEvent) case "abort_driver_setup": abortDriverSetupEvent := AbortDriverSetupEvent{} - json.Unmarshal(p, &abortDriverSetupEvent) + + if err := json.Unmarshal(p, &abortDriverSetupEvent); err != nil { + log.WithError(err).Error("Cannot unmarshal AbortDriverSetupEvent") + return nil + } i.handleAbortDriverSetupEvent(&abortDriverSetupEvent) @@ -105,7 +117,9 @@ func (i *Integration) sendEntityRemoved(e interface{}) { msg_data, } - i.sendEventMessage(&res, websocket.TextMessage) + if err := i.sendEventMessage(&res, websocket.TextMessage); err != nil { + log.WithError(err).Error("Cannot send Event Message") + } } func (i *Integration) sendEntityAvailable(e interface{}) { @@ -125,7 +139,9 @@ func (i *Integration) sendEntityAvailable(e interface{}) { // Only send event when connected, otherwise we assume this is still during setup e.g. discovering of entities if i.deviceState == ConnectedDeviceState { - i.sendEventMessage(&res, websocket.TextMessage) + if err := i.sendEventMessage(&res, websocket.TextMessage); err != nil { + log.WithError(err).Error("Cannot send Event Message") + } } } @@ -139,7 +155,9 @@ func (i *Integration) sendDeviceStateEvent() { DeviceState{DeviceId: DeviceId{DeviceId: i.DeviceId}, State: string(i.deviceState)}, } - i.sendEventMessage(&res, websocket.TextMessage) + if err := i.sendEventMessage(&res, websocket.TextMessage); err != nil { + log.WithError(err).Error("Cannot send Event Message") + } } // Emitted for all driver setup flow state changes. @@ -160,7 +178,9 @@ func (i *Integration) sendDriverSetupChangeEvent(eventType DriverSetupEventType, } } - i.sendEventMessage(&res, websocket.TextMessage) + if err := i.sendEventMessage(&res, websocket.TextMessage); err != nil { + log.WithError(err).Error("Cannot send Event Message") + } } @@ -238,7 +258,9 @@ func (i *Integration) SendEntityChangeEvent(e interface{}, a *map[string]interfa }, } - i.sendEventMessage(&res, websocket.TextMessage) + if err := i.sendEventMessage(&res, websocket.TextMessage); err != nil { + log.WithError(err).Error("Cannot send Event Message") + } } } diff --git a/pkg/integration/integration.go b/pkg/integration/integration.go index 25f20c8..8dc70a0 100644 --- a/pkg/integration/integration.go +++ b/pkg/integration/integration.go @@ -19,7 +19,7 @@ type Integration struct { Metadata *DriverMetadata - authToken string + //authToken string deviceState DState @@ -142,7 +142,9 @@ func (i *Integration) LoadSetupData() { log.WithError(err).Info("Cannot read setupDataFile") i.SetupData = make(SetupData) } else { - json.Unmarshal(file, &i.SetupData) + if err := json.Unmarshal(file, &i.SetupData); err != nil { + log.WithError(err).Error("Cannot unmarshall setSetupDataupdata") + } log.WithField("SetupData", i.SetupData).Info("Read persisted setup data") } } diff --git a/pkg/integration/register.go b/pkg/integration/register.go index b8462e3..60e63d2 100644 --- a/pkg/integration/register.go +++ b/pkg/integration/register.go @@ -100,6 +100,9 @@ func (i *Integration) registerWithRemoteTwo(remoteTwoIP string, remoteTwoPort in "DriverURL": driverURL}).Info("Register Integration with Remote Two") data, err := json.Marshal(driverRegistration) + if err != nil { + log.WithError(err).Error("Cannot unmarshal driverRegistration") + } req, err := http.NewRequest("POST", remoteTwoURL+"/api/intg/drivers", bytes.NewReader(data)) if err != nil { log.WithError(err).Fatal("impossible to build request") @@ -133,7 +136,9 @@ func (i *Integration) registerWithRemoteTwo(remoteTwoIP string, remoteTwoPort in //case http.StatusUnprocessableEntity: case http.StatusCreated: - json.Unmarshal(resBody, &driverRegistration) + if err := json.Unmarshal(resBody, &driverRegistration); err != nil { + log.WithError(err).Error("Cannot unmarshall driverRegistration") + } i.SetupData["driver_id"] = driverRegistration.DriverId i.PersistSetupData() diff --git a/pkg/integration/requests.go b/pkg/integration/requests.go index 81b46cd..8cb5414 100644 --- a/pkg/integration/requests.go +++ b/pkg/integration/requests.go @@ -17,66 +17,88 @@ func (i *Integration) handleRequest(req *RequestMessage, p []byte) { switch req.Msg { case "auth": authRequiredReq := AuthRequestMessage{} - json.Unmarshal(p, &authRequiredReq) + if err := json.Unmarshal(p, &authRequiredReq); err != nil { + log.WithError(err).Error("Cannot unmarshall authRequiredReq") + } // TODO //res = i.handleAuthRequired(&authRequiredReq) case "get_driver_version": driverVersionReq := DriverVersionReq{} - json.Unmarshal(p, &driverVersionReq) + if err := json.Unmarshal(p, &driverVersionReq); err != nil { + log.WithError(err).Error("Cannot unmarshall DriverVersionReq") + } res = i.handleGetDriverVersionRequest(&driverVersionReq) case "get_driver_metadata": driverMetadataReq := DriverMetadataReq{} - json.Unmarshal(p, &driverMetadataReq) + if err := json.Unmarshal(p, &driverMetadataReq); err != nil { + log.WithError(err).Error("Cannot unmarshall DriverMetadataReq") + } res = i.handleGetDriverMetadataRequest(&driverMetadataReq) case "get_device_state": deviceStateMessageReq := DeviceStateMessageReq{} - json.Unmarshal(p, &deviceStateMessageReq) + if err := json.Unmarshal(p, &deviceStateMessageReq); err != nil { + log.WithError(err).Error("Cannot unmarshall deviceStateMessageReq") + } i.handleGetDeviceStateRequest(&deviceStateMessageReq) case "get_available_entities": availableEntityMessageReq := AvailableEntityMessageReq{} - json.Unmarshal(p, &availableEntityMessageReq) + if err := json.Unmarshal(p, &availableEntityMessageReq); err != nil { + log.WithError(err).Error("Cannot unmarshall availableEntityMessageReq") + } res = i.handleGetAvailableEntitiesRequest(&availableEntityMessageReq) case "subscribe_events": subscribeEventMessageReq := SubscribeEventMessageReq{} - json.Unmarshal(p, &subscribeEventMessageReq) + if err := json.Unmarshal(p, &subscribeEventMessageReq); err != nil { + log.WithError(err).Error("Cannot unmarshall subscribeEventMessageReq") + } res = i.handleSubscribeEventRequest(&subscribeEventMessageReq) case "unsubscribe_events": unsubscribeEventMessageReq := UnubscribeEventMessageReq{} - json.Unmarshal(p, &unsubscribeEventMessageReq) + if err := json.Unmarshal(p, &unsubscribeEventMessageReq); err != nil { + log.WithError(err).Error("Cannot unmarshall unsubscribeEventMessageReq") + } res = i.handleUnsubscribeEventsRequest(&unsubscribeEventMessageReq) case "get_entity_states": entityStatesReq := GetEntityStatesMessageReq{} - json.Unmarshal(p, &entityStatesReq) + if err := json.Unmarshal(p, &entityStatesReq); err != nil { + log.WithError(err).Error("Cannot unmarshall entityStatesReq") + } res = i.handleGetEntityStatesRequest(&entityStatesReq) case "entity_command": entityCommandReq := EntityCommandReq{} - json.Unmarshal(p, &entityCommandReq) + if err := json.Unmarshal(p, &entityCommandReq); err != nil { + log.WithError(err).Error("Cannot unmarshall entityCommandReq") + } res = i.handleEntityCommandRequest(&entityCommandReq) case "setup_driver": setupDriverReq := SetupDriverMessageReq{} - json.Unmarshal(p, &setupDriverReq) + if err := json.Unmarshal(p, &setupDriverReq); err != nil { + log.WithError(err).Error("Cannot unmarshall setupDriverReq") + } res = i.handleSetupDriverRequest(&setupDriverReq) case "set_driver_user_data": setUserData := SetDriverUserDataRequest{} - json.Unmarshal(p, &setUserData) + if err := json.Unmarshal(p, &setUserData); err != nil { + log.WithError(err).Error("Cannot unmarshall setUserData") + } res = i.handleSetDriverUserDataRequest(&setUserData) diff --git a/pkg/integration/response.go b/pkg/integration/response.go index 8946640..0ac0dbf 100644 --- a/pkg/integration/response.go +++ b/pkg/integration/response.go @@ -18,7 +18,9 @@ func (i *Integration) sendResponseMessage(res interface{}, messageType int) erro // Unmarshal againinto Event Message for some fields response := ResponseMessage{} - json.Unmarshal(msg, &response) + if err := json.Unmarshal(msg, &response); err != nil { + log.WithError(err).Error("Cannot unmarshal response") + } log.WithFields(log.Fields{ "Message": response.Msg, @@ -56,5 +58,7 @@ func (i *Integration) authenticationResponseMessage(code int) *AuthenticationRes // Send a AuthenticationResponse Message func (i *Integration) SendAuthenticationResponse() { msg := i.authenticationResponseMessage(200) - i.sendResponseMessage(msg, websocket.TextMessage) + if err := i.sendResponseMessage(msg, websocket.TextMessage); err != nil { + log.WithError(err).Error("Cannot send Response Message") + } } diff --git a/pkg/integration/settingtypes.go b/pkg/integration/settingtypes.go index 1f3a382..071e5bc 100644 --- a/pkg/integration/settingtypes.go +++ b/pkg/integration/settingtypes.go @@ -9,7 +9,7 @@ type SettingTypeNumberDefinition struct { Min float64 `json:"min,omitempty"` Max float64 `json:"max,omitempty"` Step float64 `json:"step,omitempty"` - Decimals int `json:"decimal,omitemptys"` + Decimals int `json:"decimal,omitempty"` Unit LanguageText `json:"unit"` } diff --git a/pkg/integration/types.go b/pkg/integration/types.go index 6e65093..33a87ef 100644 --- a/pkg/integration/types.go +++ b/pkg/integration/types.go @@ -62,24 +62,24 @@ type DriverSetupError string const ( SetupState DriverSetupState = "SETUP" - WaitUserActionState = "WAIT_USER_ACTION" - OkState = "OK" - ErrorState = "ERROR" + WaitUserActionState DriverSetupState = "WAIT_USER_ACTION" + OkState DriverSetupState = "OK" + ErrorState DriverSetupState = "ERROR" ) const ( StartEvent DriverSetupEventType = "START" - SetupEvent = "SETUP" - StopEvent = "STOP" + SetupEvent DriverSetupEventType = "SETUP" + StopEvent DriverSetupEventType = "STOP" ) const ( NoneError DriverSetupError = "NONE" - NotFoundError = "NOT_FOUND" - ConnectionRefusedError = "CONNECTION_REFUSED" - AuthErrorError = "AUTHORIZATION_ERROR" - TimeoutError = "TIMEOUT" - OtherError = "OTHER" + NotFoundError DriverSetupError = "NOT_FOUND" + ConnectionRefusedError DriverSetupError = "CONNECTION_REFUSED" + AuthErrorError DriverSetupError = "AUTHORIZATION_ERROR" + TimeoutError DriverSetupError = "TIMEOUT" + OtherError DriverSetupError = "OTHER" ) type AvailableEntityFilter struct { diff --git a/pkg/integration/websocket.go b/pkg/integration/websocket.go index e09e2f1..259dcc4 100644 --- a/pkg/integration/websocket.go +++ b/pkg/integration/websocket.go @@ -53,9 +53,13 @@ func (i *Integration) wsEndpoint(w http.ResponseWriter, r *http.Request) { func (i *Integration) wsReader(ws *websocket.Conn) { log.WithField("RemoteAddr", ws.RemoteAddr().String()).Debug("Start Websocket read loop") ws.SetReadLimit(maxMessageSize) - ws.SetReadDeadline(time.Now().Add(pongWait)) + if err := ws.SetReadDeadline(time.Now().Add(pongWait)); err != nil { + log.WithError(err).Error("Cannot set readdeadline") + } ws.SetPongHandler(func(string) error { - ws.SetReadDeadline(time.Now().Add(pongWait)) + if err := ws.SetReadDeadline(time.Now().Add(pongWait)); err != nil { + log.WithError(err).Error("Cannot set readdeadline") + } return nil }) @@ -141,7 +145,10 @@ func (i *Integration) wsWriter(ws *websocket.Conn) { } case <-ticker.C: - ws.SetWriteDeadline(time.Now().Add(writeWait)) + + if err := ws.SetWriteDeadline(time.Now().Add(writeWait)); err != nil { + log.WithError(err).Error("Cannot set writedealine") + } log.WithField("RemoteAddr", ws.RemoteAddr().String()).Debug("Send Ping Message") if err := ws.WriteMessage(websocket.PingMessage, nil); err != nil { log.WithField("RemoteAddr", ws.RemoteAddr().String()).Info("Could not send Ping message") diff --git a/pkg/shelly/shelly.go b/pkg/shelly/shelly.go index 3254415..64818e7 100644 --- a/pkg/shelly/shelly.go +++ b/pkg/shelly/shelly.go @@ -50,7 +50,9 @@ func (s *Shelly) StartDiscovery() { s.subscribeMqttTopic("shellies/announce", s.mqttDiscoverCallback()) s.subscribeMqttTopic("shellies/+/info", s.mqttDiscoverCallback()) - s.publishMqttCommand("shellies/command", "announce") + if err := s.publishMqttCommand("shellies/command", "announce"); err != nil { + log.WithError(err).Error("Cannot publish MQTT Command") + } } func (s *Shelly) StopDiscovery() {