从 homeassistant 访问 USB 时出现权限错误 docker

Permission error accessing USB from homeassistant docker

我是 运行 家庭助理,在 RPi 4 的 docker 容器中 Raspbian。我正在使用 tributs scripts to elevate the need of running the docker image as root. This all works dandy. But now I am trying to add the dsmr integration 但我没有成功。集成需要通过 USB 连接到“Slimme meter”。但是,我收到权限错误。我对 docker 和 linux 特权的了解太有限,不知道从哪里开始调试它。有人能指点我吗?

这是 homeassistant 向我抛出的错误消息:

Logger: homeassistant.components.dsmr
Source: components/dsmr/config_flow.py:93
Integration: dsmr (documentation, issues)
First occurred: 21:18:17 (1 occurrences)
Last logged: 21:18:17

Error connecting to DSMR
Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/serial/serialposix.py", line 322, in open
    self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
PermissionError: [Errno 13] Permission denied: '/dev/ttyUSB0'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/dsmr/config_flow.py", line 93, in validate_connect
    transport, protocol = await asyncio.create_task(reader_factory())
  File "/usr/local/lib/python3.9/site-packages/serial_asyncio/__init__.py", line 445, in create_serial_connection
    serial_instance = serial.serial_for_url(*args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/serial/__init__.py", line 90, in serial_for_url
    instance.open()
  File "/usr/local/lib/python3.9/site-packages/serial/serialposix.py", line 325, in open
    raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg))
serial.serialutil.SerialException: [Errno 13] could not open port /dev/ttyUSB0: [Errno 13] Permission denied: '/dev/ttyUSB0'

经过一番研究后,我认为我需要将用户添加到一个名为 dialout 的额外组中,因为只有该组的成员才能访问 USB 端口(以及其他设备)。

首先我通过运行

计算出宿主机(机器运行 docker容器)中dialout组的组id
cat /etc/group | grep dialout

在我的例子中它返回了 20。幸运的是,tributs has the possibility to add the user to an extra group via the environment variable EXTRA_GID. So all the relevant lines in the docker-compose file for accessing USB are (when using the script of tribut) 的脚本是:

    devices:
      - /dev/ttyUSB0:/dev/ttyUSB0
    environment:
      - PUID=1000
      - PGID=1000
      - EXTRA_GID=20  # this is the ID of the group 'dialout'