Repository: home-assistant/core
Pull request: Fix slave id equal to 0
<!--
  You are amazing! Thanks for contributing to our project!
  Please, DO NOT DELETE ANY TEXT from this template! (unless instructed).
-->
## Breaking change
<!--
  If your PR contains a breaking change for existing users, it is important
  to tell them what breaks, how to make it work again and why we did this.
  This piece of text is published with the release notes, so it helps if you
  write it towards our users, not us.
  Note: Remove this section if this PR is NOT a breaking change.
-->
**Possible breaking change**: 
The configuration where the slave id or the device_address was not set, now assume a default value equal to 1 (instead of 0). 
The situation can be easily fixed by an explicit declaration of the parameter. 
**Please note that the current bug has already broken those situations**. 

## Proposed change
<!--
  Describe the big picture of your changes here to communicate to the
  maintainers why we should accept this pull request. If it fixes a bug
  or resolves a feature request, be sure to link to that issue in the
  additional information section.
-->

After having bumped pymodbus 3.7.x an hidden bug belonging the case where the slave id is set to 0 or not set at all became visible. 
Before of that change, the underlying library pymodbus in case of missing slave id used a default value equal to 0.  From the version 3.7.x, pymodbus changed the defaul slave it to 1, enforcing the fact that the slave id 0 is defined as broadcast according with the [ModBus protocol](https://modbus.org/specs.php). 
This change within the library highlighted a previously hidden bug in the integration where a condition to check if the slave ID was None, actually intercepted even a slave id set to 0, 
Fixing the bug, we align also the integration with the Modbus spec and with the pymodbus library setting the default value for the slave id to 1, instead of 0. 

## Type of change
<!--
  What type of change does your PR introduce to Home Assistant?
  NOTE: Please, check only 1! box!
  If your PR requires multiple boxes to be checked, you'll most likely need to
  split it into multiple PRs. This makes things easier and faster to code review.
-->

- [ ] Dependency upgrade
- [X] Bugfix (non-breaking change which fixes an issue)
- [ ] New integration (thank you!)
- [ ] New feature (which adds functionality to an existing integration)
- [ ] Deprecation (breaking change to happen in the future)
- [ ] Breaking change (fix/feature causing existing functionality to break)
- [ ] Code quality improvements to existing code or addition of tests

## Additional information
<!--
  Details are important, and help maintainers processing your PR.
  Please be sure to fill out additional details, if applicable.
-->

- This PR fixes or closes issue: fixes #134665
- This PR is related to issue: 
- Link to documentation pull request: 

## Checklist
<!--
  Put an `x` in the boxes that apply. You can also fill these out after
  creating the PR. If you're unsure about any of them, don't hesitate to ask.
  We're here to help! This is simply a reminder of what we are going to look
  for before merging your code.
-->

- [X] The code change is tested and works locally.
- [X] Local tests pass. **Your PR cannot be merged unless tests pass**
- [X] There is no commented out code in this PR.
- [X] I have followed the [development checklist][dev-checklist]
- [X] I have followed the [perfect PR recommendations][perfect-pr]
- [X] The code has been formatted using Ruff (`ruff format homeassistant tests`)
- [ ] Tests have been added to verify that the new code works.

If user exposed functionality or configuration variables are added/changed:

- [ ] Documentation added/updated for [www.home-assistant.io][docs-repository]

If the code communicates with devices, web services, or third-party tools:

- [ ] The [manifest file][manifest-docs] has all fields filled out correctly.  
      Updated and included derived files by running: `python3 -m script.hassfest`.
- [ ] New or updated dependencies have been added to `requirements_all.txt`.  
      Updated by running `python3 -m script.gen_requirements_all`.
- [ ] For the updated dependencies - a link to the changelog, or at minimum a diff between library versions is added to the PR description.

<!--
  This project is very active and we have a high turnover of pull requests.

  Unfortunately, the number of incoming pull requests is higher than what our
  reviewers can review and merge so there is a long backlog of pull requests
  waiting for review. You can help here!
  
  By reviewing another pull request, you will help raise the code quality of
  that pull request and the final review will be faster. This way the general
  pace of pull request reviews will go up and your wait time will go down.
  
  When picking a pull request to review, try to choose one that hasn't yet
  been reviewed.

  Thanks for helping out!
-->

To help with the load of incoming pull requests:

- [X] I have reviewed two other [open pull requests][prs] in this repository.

[prs]: https://github.com/home-assistant/core/pulls?q=is%3Aopen+is%3Apr+-author%3A%40me+-draft%3Atrue+-label%3Awaiting-for-upstream+sort%3Acreated-desc+review%3Anone+-status%3Afailure

<!--
  Thank you for contributing <3

  Below, some useful links you could explore:
-->
[dev-checklist]: https://developers.home-assistant.io/docs/development_checklist/
[manifest-docs]: https://developers.home-assistant.io/docs/creating_integration_manifest/
[quality-scale]: https://developers.home-assistant.io/docs/integration_quality_scale_index/
[docs-repository]: https://github.com/home-assistant/home-assistant.io
[perfect-pr]: https://developers.home-assistant.io/docs/review-process/#creating-the-perfect-pr


Problem statement:
Modbus Integration Error for Slave ID 0 After Upgrade to Home Assistant 2025.1
### The problem

After upgrading to Home Assistant version 2025.1, the Modbus integration started failing for a specific device with slave ID 0. Other Modbus devices configured in Home Assistant continue to work without issues. The following error is logged:

```
2025-01-04 13:43:35.328 ERROR (MainThread) [homeassistant.components.modbus.modbus] Pymodbus: huaweismartlogger: Error: device: 0 address: 40560 -> Exception Response(131, 3, IllegalValue)
```

The error appears to be related to the Modbus slave with ID 0. The Exception Response includes function code 3 and exception code IllegalValue. This issue did not occur prior to the upgrade.

### What version of Home Assistant Core has the issue?

core-2025.1.0

### What was the last working version of Home Assistant Core?

core-2024.12.5

### What type of installation are you running?

Home Assistant OS

### Integration causing the issue

modbus

### Link to integration documentation on our website

_No response_

### Diagnostics information

_No response_

### Example YAML snippet

```yaml
- name: SmartLogger Active Power
      unique_id: smartLogger_active_power
      unit_of_measurement: W
      device_class: power
      data_type: int32
      address: 40525
      scan_interval: 15
      slave: 0
      input_type: holding
    - name: SmartLogger Input Power
      unique_id: smartLogger_input_power
      unit_of_measurement: W
      device_class: power
      data_type: int32
      address: 40521
      scan_interval: 5
      slave: 0
      input_type: holding
```


### Anything in the logs that might be useful for us?

```txt
2025-01-04 13:43:35.328 ERROR (MainThread) [homeassistant.components.modbus.modbus] Pymodbus: huaweismartlogger: Error: device: 0 address: 40560 -> Exception Response(131, 3, IllegalValue)
2025-01-04 13:43:36.601 ERROR (MainThread) [homeassistant.components.modbus.modbus] Pymodbus: huaweismartlogger: Error: device: 0 address: 40562 -> Exception Response(131, 3, IllegalValue)
2025-01-04 13:43:36.735 ERROR (MainThread) [homeassistant.components.modbus.modbus] Pymodbus: huaweismartlogger: Error: device: 0 address: 40544 -> Exception Response(131, 3, IllegalValue)
2025-01-04 13:43:36.845 ERROR (MainThread) [homeassistant.components.modbus.modbus] Pymodbus: huaweismartlogger: Error: device: 0 address: 40532 -> Exception Response(131, 3, IllegalValue)
2025-01-04 13:44:06.734 ERROR (MainThread) [homeassistant.components.modbus.modbus] Pymodbus: huaweismartlogger: Error: device: 0 address: 40532 -> Exception Response(131, 3, IllegalValue)
2025-01-04 13:44:35.512 ERROR (MainThread) [homeassistant.components.modbus.modbus] Pymodbus: huaweismartlogger: Error: device: 0 address: 40685 -> Exception Response(131, 3, IllegalValue)
2025-01-04 13:44:36.736 ERROR (MainThread) [homeassistant.components.modbus.modbus] Pymodbus: huaweismartlogger: Error: device: 0 address: 40544 -> Exception Response(131, 3, IllegalValue)
2025-01-04 13:44:36.757 ERROR (MainThread) [homeassistant.components.modbus.modbus] Pymodbus: huaweismartlogger: Error: device: 0 address: 40532 -> Exception Response(131, 3, IllegalValue)
2025-01-04 13:45:06.739 ERROR (MainThread) [homeassistant.components.modbus.modbus] Pymodbus: huaweismartlogger: Error: device: 0 address: 40532 -> Exception Response(131, 3, IllegalValue)
2025-01-04 13:45:35.507 ERROR (MainThread) [homeassistant.components.modbus.modbus] Pymodbus: huaweismartlogger: Error: device: 0 address: 40560 -> Exception Response(131, 3, IllegalValue)
2025-01-04 13:45:36.083 ERROR (MainThread) [homeassistant.components.modbus.modbus] Pymodbus: huaweismartlogger: Error: device: 0 address: 40564 -> Exception Response(131, 3, IllegalValue)
2025-01-04 13:45:36.734 ERROR (MainThread) [homeassistant.components.modbus.modbus] Pymodbus: huaweismartlogger: Error: device: 0 address: 40544 -> Exception Response(131, 3, IllegalValue)
2025-01-04 13:45:36.754 ERROR (MainThread) [homeassistant.components.modbus.modbus] Pymodbus: huaweismartlogger: Error: device: 0 address: 40532 -> Exception Response(131, 3, IllegalValue)
2025-01-04 13:46:05.559 ERROR (MainThread) [homeassistant.components.modbus.modbus] Pymodbus: huaweismartlogger: Error: device: 0 address: 40685 -> Exception Response(131, 3, IllegalValue)
2025-01-04 13:46:06.741 ERROR (MainThread) [homeassistant.components.modbus.modbus] Pymodbus: huaweismartlogger: Error: device: 0 address: 40532 -> Exception Response(131, 3, IllegalValue)
2025-01-04 13:46:36.735 ERROR (MainThread) [homeassistant.components.modbus.modbus] Pymodbus: huaweismartlogger: Error: device: 0 address: 40544 -> Exception Response(131, 3, IllegalValue)
```


### Additional information

_No response_

Hints from issue discussion:
[modbus documentation](https://www.home-assistant.io/integrations/modbus)
[modbus source](https://github.com/home-assistant/core/tree/dev/homeassistant/components/modbus)
I believe I am having somewhat of a similar issue with a custom modbus integration.

All of a sudden after installing 2025.1.0 my sensors are no longer working. 

modbus:
  - name: Sungrow SG5.0RS
    type: tcp
    host: !secret sungrow_modbus_host_ip
    port: !secret sungrow_modbus_port
    sensors:
      - name: Inverter Device Type Code
        unique_id: inverter_device_type_code
        device_address: !secret sungrow_modbus_slave
        address: 4999 # reg 5000
        input_type: input
        data_type: uint16
        scan_interval: 1200
@axelfair89 your slave id is 0?
Hmm no slave ID is 1. Downgrading to 2024.12.5 fixed the issue. 
Same issue here. Update to 2025.1.0 crash my modbus. (victron) 
I have the same problem.

This is my modbus config:
```
modbus:
  - name: WallBe
    type: tcp
    host: 192.168.178.106
    port: 502
    
    delay: 0
    message_wait_milliseconds: 30
    timeout: 5
    
    sensors:
      - name: Wallbox Status
        unique_id: WallboxStatus
        address: 100
        data_type: string
        count: 1
      - name: Wallbox LadeLeistung
        unique_id: WallboxLadeLeistung
        address: 132
        data_type: float32
        unit_of_measurement: W
        device_class: power
      - name: Wallbox LadebedingungenOK
        unique_id: WallboxLadebedingungenOK
        address: 204
        data_type: float16
      - name: Wallbox Ladestrom
        unique_id: WallboxLadestrom
        address: 300
        data_type: float16
        unit_of_measurement: A
```

And here is the debug log from the Modbus module - maybe it will help

[home-assistant_modbus_2025-01-05T12-56-36.043Z.log](https://github.com/user-attachments/files/18310277/home-assistant_modbus_2025-01-05T12-56-36.043Z.log)

I can confirm, my problem was the slave id 0, I manage to change it on the device to id 7, and it's working.
> I can confirm, my problem was the slave id 0, I manage to change it on the device to id 7, and it's working.

Unfortunately, I can't change this in the wallbox. So I need a fix for the problem

I had the same problem as stated in this and other issues.  I ended up restoring to the previous HA verson to get modbus to work again.  
The feedback from etofi above got me thinking that maybe the reason his worked after changing the slave to 7 was because he added slave 7 after the upgrade to HA.  So I did some testing on another non critical HA I have to attempt to get modbus to work with the ugrade to 2025.1.  
To cut to the chase, I found if I remove modbus before upgrading to 2025.1 then adding modbus back in after the uograde to 2025.1, modbus works on 2025.1 version.  It is also possibe that removing modbus after the upgrade to 2025.1 then restarting HA then adding modbus back in might work too but I did not try that.
This may not be the long term solution but it worked for me and at least allows me to continue to use 2025.1 and modbus.
In case of no slave address defined, previously modbus set it as 0. This was an error, because slave id 0 si reserved and identified as broadcast address. Starting version 2025.1, the default address is 1, so this is the reason why slave 7 works. 
@leovanderburgt , what is the integration/configuration that it is giving you the problem?

Commit message: fix default 1

Patch to review:
diff --git a/homeassistant/components/modbus/entity.py b/homeassistant/components/modbus/entity.py
index 03bcc98de40ec..80fd45cd4035d 100644
--- a/homeassistant/components/modbus/entity.py
+++ b/homeassistant/components/modbus/entity.py
@@ -79,7 +79,7 @@ def __init__(
         """Initialize the Modbus binary sensor."""
 
         self._hub = hub
-        self._slave = entry.get(CONF_SLAVE) or entry.get(CONF_DEVICE_ADDRESS, 0)
+        self._slave = entry.get(CONF_SLAVE) or entry.get(CONF_DEVICE_ADDRESS, 1)
         self._address = int(entry[CONF_ADDRESS])
         self._input_type = entry[CONF_INPUT_TYPE]
         self._value: str | None = None
diff --git a/homeassistant/components/modbus/modbus.py b/homeassistant/components/modbus/modbus.py
index c18a256a1cf91..cd216fc05ab80 100644
--- a/homeassistant/components/modbus/modbus.py
+++ b/homeassistant/components/modbus/modbus.py
@@ -378,7 +378,7 @@ async def low_level_pb_call(
         self, slave: int | None, address: int, value: int | list[int], use_call: str
     ) -> ModbusPDU | None:
         """Call sync. pymodbus."""
-        kwargs: dict[str, Any] = {"slave": slave} if slave else {}
+        kwargs: dict[str, Any] = {"slave": slave} if slave is not None else {"slave": 1}
         entry = self._pb_request[use_call]
         kwargs[entry.value_attr_name] = value
         try:


Code review comments:
diff_hunk: @@ -79,7 +79,7 @@ def __init__(
         """Initialize the Modbus binary sensor."""
 
         self._hub = hub
-        self._slave = entry.get(CONF_SLAVE) or entry.get(CONF_DEVICE_ADDRESS, 0)
+        self._slave = entry.get(CONF_SLAVE) or entry.get(CONF_DEVICE_ADDRESS, 1)
path: homeassistant/components/modbus/entity.py
text: @user1:
Can CONF_SLAVE ever legitimately be 0?

@author:
Theorically an user could use 0 (for device_address or slave)  for broadcasting or, according to [pymodbus client](https://pymodbus.readthedocs.io/en/latest/source/client.html#client-device-addressing) documentation as standard slave. 
This fix makes this an explicit choice as already done by pymodbus. 

@user1:
if `CONF_SLAVE` is set to 0 the right hand of the `or` will always evaluate instead. Should it be a `None` check here?

@author:
You're right. None and 0 will be evaluated both as False. Fixed. Thanks @user1 
Introduced also the slave id as attribute of the entity. It could be useful for a final user.
Added a test