mtdx62-modbus-library 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. mtdx62_modbus_library-0.3.0/.github/workflows/ci.yaml +28 -0
  2. mtdx62_modbus_library-0.3.0/.github/workflows/publish.yml +27 -0
  3. mtdx62_modbus_library-0.3.0/.gitignore +24 -0
  4. mtdx62_modbus_library-0.3.0/LICENSE +21 -0
  5. mtdx62_modbus_library-0.3.0/PKG-INFO +140 -0
  6. mtdx62_modbus_library-0.3.0/README.md +113 -0
  7. mtdx62_modbus_library-0.3.0/openspec/changes/archive/2026-11-24-add-mtdx62-device-library/.openspec.yaml +2 -0
  8. mtdx62_modbus_library-0.3.0/openspec/changes/archive/2026-11-24-add-mtdx62-device-library/design.md +158 -0
  9. mtdx62_modbus_library-0.3.0/openspec/changes/archive/2026-11-24-add-mtdx62-device-library/proposal.md +48 -0
  10. mtdx62_modbus_library-0.3.0/openspec/changes/archive/2026-11-24-add-mtdx62-device-library/specs/mtdx62-registers/spec.md +169 -0
  11. mtdx62_modbus_library-0.3.0/openspec/changes/archive/2026-11-24-add-mtdx62-device-library/tasks.md +13 -0
  12. mtdx62_modbus_library-0.3.0/openspec/changes/archive/2026-11-24-fix-device-status-codes/.openspec.yaml +2 -0
  13. mtdx62_modbus_library-0.3.0/openspec/changes/archive/2026-11-24-fix-device-status-codes/design.md +91 -0
  14. mtdx62_modbus_library-0.3.0/openspec/changes/archive/2026-11-24-fix-device-status-codes/proposal.md +38 -0
  15. mtdx62_modbus_library-0.3.0/openspec/changes/archive/2026-11-24-fix-device-status-codes/specs/mtdx62-registers/spec.md +64 -0
  16. mtdx62_modbus_library-0.3.0/openspec/changes/archive/2026-11-24-fix-device-status-codes/tasks.md +9 -0
  17. mtdx62_modbus_library-0.3.0/openspec/changes/archive/2026-11-24-rename-library-package/.openspec.yaml +2 -0
  18. mtdx62_modbus_library-0.3.0/openspec/changes/archive/2026-11-24-rename-library-package/design.md +72 -0
  19. mtdx62_modbus_library-0.3.0/openspec/changes/archive/2026-11-24-rename-library-package/proposal.md +41 -0
  20. mtdx62_modbus_library-0.3.0/openspec/changes/archive/2026-11-24-rename-library-package/specs/mtdx62-registers/spec.md +28 -0
  21. mtdx62_modbus_library-0.3.0/openspec/changes/archive/2026-11-24-rename-library-package/tasks.md +9 -0
  22. mtdx62_modbus_library-0.3.0/openspec/config.yaml +37 -0
  23. mtdx62_modbus_library-0.3.0/openspec/specs/mtdx62-registers/spec.md +234 -0
  24. mtdx62_modbus_library-0.3.0/pyproject.toml +56 -0
  25. mtdx62_modbus_library-0.3.0/src/mtdx62_modbus_library/__init__.py +24 -0
  26. mtdx62_modbus_library-0.3.0/src/mtdx62_modbus_library/const.py +58 -0
  27. mtdx62_modbus_library-0.3.0/src/mtdx62_modbus_library/device.py +49 -0
  28. mtdx62_modbus_library-0.3.0/src/mtdx62_modbus_library/py.typed +0 -0
  29. mtdx62_modbus_library-0.3.0/src/mtdx62_modbus_library/readings.py +80 -0
  30. mtdx62_modbus_library-0.3.0/src/mtdx62_modbus_library/settings.py +70 -0
  31. mtdx62_modbus_library-0.3.0/tests/test_device.py +58 -0
  32. mtdx62_modbus_library-0.3.0/tests/test_readings.py +173 -0
  33. mtdx62_modbus_library-0.3.0/tests/test_settings.py +75 -0
@@ -0,0 +1,28 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ jobs:
9
+ test:
10
+ name: lint, typing, tests
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - uses: actions/checkout@v4
14
+ - uses: actions/setup-python@v5
15
+ with:
16
+ python-version: "3.14"
17
+ - name: Install
18
+ run: |
19
+ python -m pip install --upgrade pip
20
+ pip install -e ".[test]"
21
+ - name: Ruff format
22
+ run: ruff format --check .
23
+ - name: Ruff check
24
+ run: ruff check .
25
+ - name: mypy
26
+ run: mypy
27
+ - name: pytest
28
+ run: pytest --cov=mtdx62_modbus_library --cov-report=term-missing --cov-fail-under=95
@@ -0,0 +1,27 @@
1
+ name: Release
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+ workflow_dispatch:
7
+
8
+ jobs:
9
+ pypi:
10
+ name: publish to PyPI
11
+ runs-on: ubuntu-latest
12
+ environment:
13
+ name: pypi
14
+ url: https://pypi.org/p/mtdx62-modbus-library
15
+ permissions:
16
+ id-token: write
17
+ steps:
18
+ - uses: actions/checkout@v4
19
+ - uses: actions/setup-python@v5
20
+ with:
21
+ python-version: "3.14"
22
+ - name: Build
23
+ run: |
24
+ python -m pip install --upgrade pip build
25
+ python -m build
26
+ - name: Publish
27
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,24 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ .venv/
6
+ build/
7
+ dist/
8
+ .pytest_cache/
9
+ .mypy_cache/
10
+ .ruff_cache/
11
+ htmlcov/
12
+ .coverage
13
+ .coverage.*
14
+ coverage.xml
15
+
16
+ # Редакторы и ОС
17
+ .vscode/
18
+ .idea/
19
+ Thumbs.db
20
+ desktop.ini
21
+ .DS_Store
22
+
23
+ # Локальные секреты
24
+ .env
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sergey Astakhov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,140 @@
1
+ Metadata-Version: 2.5
2
+ Name: mtdx62-modbus-library
3
+ Version: 0.3.0
4
+ Summary: Device library for the MTD062-MB and MTD262-MB Modbus presence sensors
5
+ Project-URL: Homepage, https://github.com/sergeyastakhov/mtdx62-modbus-library
6
+ Project-URL: Repository, https://github.com/sergeyastakhov/mtdx62-modbus-library
7
+ Project-URL: Issues, https://github.com/sergeyastakhov/mtdx62-modbus-library/issues
8
+ Project-URL: Changelog, https://github.com/sergeyastakhov/mtdx62-modbus-library/releases
9
+ Author-email: Sergey Astakhov <sergeyastakhov@mail.ru>
10
+ License: MIT
11
+ License-File: LICENSE
12
+ Keywords: home assistant,modbus,presence sensor,radar
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.14
19
+ Requires-Dist: modbus-connection<5,>=4.12.4
20
+ Provides-Extra: test
21
+ Requires-Dist: mypy>=1.13; extra == 'test'
22
+ Requires-Dist: pytest-asyncio>=1.0; extra == 'test'
23
+ Requires-Dist: pytest-cov>=6.0; extra == 'test'
24
+ Requires-Dist: pytest>=8.3; extra == 'test'
25
+ Requires-Dist: ruff>=0.9; extra == 'test'
26
+ Description-Content-Type: text/markdown
27
+
28
+ # mtdx62
29
+
30
+ Device library for the **MTD062-MB** (5.8 GHz) and **MTD262-MB** (24 GHz) human presence
31
+ sensors, spoken to over Modbus RTU or Modbus TCP.
32
+
33
+ The library models the sensor's registers as typed Python attributes. It reads the whole
34
+ measurement block in one Modbus request and keeps the configuration registers separate, so
35
+ polling the sensor does not drag along parameters that rarely change.
36
+
37
+ Built on [`modbus-connection`](https://home-assistant-libs.github.io/modbus-connection/): the
38
+ caller owns the connection and hands over a `ModbusUnit`. The library never opens a socket or a
39
+ serial port and has no dependency on Home Assistant.
40
+
41
+ ## Install
42
+
43
+ ```bash
44
+ pip install mtdx62-modbus-library
45
+ ```
46
+
47
+ ## Use
48
+
49
+ ```python
50
+ import asyncio
51
+
52
+ from modbus_connection import ModbusTcpParams
53
+ from modbus_connection.tmodbus import ModbusConnection
54
+ from mtdx62_modbus_library import Mtdx62Device
55
+
56
+
57
+ async def main() -> None:
58
+ connection = ModbusConnection(ModbusTcpParams(host="192.168.1.50", port=502))
59
+ try:
60
+ device = Mtdx62Device(connection.for_unit(1))
61
+
62
+ await device.async_update_readings()
63
+ print(device.readings.presence, device.readings.illuminance, device.readings.distance)
64
+
65
+ await device.async_update_settings()
66
+ print(device.settings.detection_distance, device.settings.departure_delay)
67
+ finally:
68
+ await connection.close()
69
+
70
+
71
+ asyncio.run(main())
72
+ ```
73
+
74
+ ## What it exposes
75
+
76
+ | Attribute | Meaning | Unit |
77
+ |---|---|---|
78
+ | `readings.presence` | a person is detected, including someone sitting still | — |
79
+ | `readings.illuminance` | ambient light as the sensor sees it | lx |
80
+ | `readings.distance` | distance to the detected target | m, centimetre resolution |
81
+ | `readings.status_code` | raw health code | — |
82
+ | `readings.status` | health code as `DeviceStatus`, `None` when unknown | — || `readings.app_version` | application firmware version, `1.2.3` | — |
83
+ | `readings.radar_version` | radar module firmware version | — |
84
+ | `settings.*` | detection range, delays, sensitivities, bus address and speed | see `Settings` |
85
+
86
+ Every attribute is `None` until the first read of its sub-system.
87
+
88
+ The library only reads: no field is writable, and the sensor's configuration is not changed by
89
+ it. Reading the configuration is a separate call (`async_update_settings()`) precisely so that a
90
+ 5-second poll costs one request.
91
+
92
+ ## Health codes
93
+
94
+ `readings.status` is a `DeviceStatus` member. A running sensor reports `OK` (1); code 0 is the
95
+ transient self-check at power-up, and code 2 and above mean the sensor is broken. `is_fault`
96
+ tells the two groups apart, so consumers do not have to remember the boundary.
97
+
98
+ | Code | Meaning | `is_fault` |
99
+ |---|---|---|
100
+ | 0 | self-check in progress | no |
101
+ | 1 | running | no |
102
+ | 2 | self-test failed | yes |
103
+ | 3 | other fault | yes |
104
+ | 4 | radar module fault | yes |
105
+ | 5 | RS485 fault | yes |
106
+ | 6 | radar and RS485 fault | yes |
107
+
108
+ An undocumented code decodes to `None`, while `status_code` keeps the raw number for diagnostics.
109
+
110
+ > **0.2.0 is a breaking release**: `OK` and `SELF_TEST_FAILED` swapped values, because 0.1.0 read
111
+ > the vendor table one row off.
112
+
113
+ ## Errors
114
+
115
+ The library raises whatever `modbus-connection` raises: a timeout, a protocol error, or a
116
+ refusal of the addressed registers. It does not wrap them, so the caller can tell a dead link
117
+ from a slow device.
118
+
119
+ ## Supported firmware
120
+
121
+ Written against the vendor documentation for firmware **1.6**. The register map is in
122
+ `openspec/specs/mtdx62-registers/` once the first change is archived, and the raw facts are in
123
+ `references/mtdx62/DEVICE-FACTS.md` in the project workspace.
124
+
125
+ ## Tests
126
+
127
+ Tests run against the in-memory backend of `modbus-connection`, so they need neither hardware
128
+ nor Home Assistant:
129
+
130
+ ```bash
131
+ pip install -e ".[test]"
132
+ pytest
133
+ ```
134
+
135
+ ## Author
136
+
137
+ Sergey Astakhov — [sergeyastakhov@mail.ru](mailto:sergeyastakhov@mail.ru),
138
+ [github.com/sergeyastakhov](https://github.com/sergeyastakhov).
139
+
140
+ Source and issues: <https://github.com/sergeyastakhov/mtdx62-modbus-library>. MIT licensed.
@@ -0,0 +1,113 @@
1
+ # mtdx62
2
+
3
+ Device library for the **MTD062-MB** (5.8 GHz) and **MTD262-MB** (24 GHz) human presence
4
+ sensors, spoken to over Modbus RTU or Modbus TCP.
5
+
6
+ The library models the sensor's registers as typed Python attributes. It reads the whole
7
+ measurement block in one Modbus request and keeps the configuration registers separate, so
8
+ polling the sensor does not drag along parameters that rarely change.
9
+
10
+ Built on [`modbus-connection`](https://home-assistant-libs.github.io/modbus-connection/): the
11
+ caller owns the connection and hands over a `ModbusUnit`. The library never opens a socket or a
12
+ serial port and has no dependency on Home Assistant.
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ pip install mtdx62-modbus-library
18
+ ```
19
+
20
+ ## Use
21
+
22
+ ```python
23
+ import asyncio
24
+
25
+ from modbus_connection import ModbusTcpParams
26
+ from modbus_connection.tmodbus import ModbusConnection
27
+ from mtdx62_modbus_library import Mtdx62Device
28
+
29
+
30
+ async def main() -> None:
31
+ connection = ModbusConnection(ModbusTcpParams(host="192.168.1.50", port=502))
32
+ try:
33
+ device = Mtdx62Device(connection.for_unit(1))
34
+
35
+ await device.async_update_readings()
36
+ print(device.readings.presence, device.readings.illuminance, device.readings.distance)
37
+
38
+ await device.async_update_settings()
39
+ print(device.settings.detection_distance, device.settings.departure_delay)
40
+ finally:
41
+ await connection.close()
42
+
43
+
44
+ asyncio.run(main())
45
+ ```
46
+
47
+ ## What it exposes
48
+
49
+ | Attribute | Meaning | Unit |
50
+ |---|---|---|
51
+ | `readings.presence` | a person is detected, including someone sitting still | — |
52
+ | `readings.illuminance` | ambient light as the sensor sees it | lx |
53
+ | `readings.distance` | distance to the detected target | m, centimetre resolution |
54
+ | `readings.status_code` | raw health code | — |
55
+ | `readings.status` | health code as `DeviceStatus`, `None` when unknown | — || `readings.app_version` | application firmware version, `1.2.3` | — |
56
+ | `readings.radar_version` | radar module firmware version | — |
57
+ | `settings.*` | detection range, delays, sensitivities, bus address and speed | see `Settings` |
58
+
59
+ Every attribute is `None` until the first read of its sub-system.
60
+
61
+ The library only reads: no field is writable, and the sensor's configuration is not changed by
62
+ it. Reading the configuration is a separate call (`async_update_settings()`) precisely so that a
63
+ 5-second poll costs one request.
64
+
65
+ ## Health codes
66
+
67
+ `readings.status` is a `DeviceStatus` member. A running sensor reports `OK` (1); code 0 is the
68
+ transient self-check at power-up, and code 2 and above mean the sensor is broken. `is_fault`
69
+ tells the two groups apart, so consumers do not have to remember the boundary.
70
+
71
+ | Code | Meaning | `is_fault` |
72
+ |---|---|---|
73
+ | 0 | self-check in progress | no |
74
+ | 1 | running | no |
75
+ | 2 | self-test failed | yes |
76
+ | 3 | other fault | yes |
77
+ | 4 | radar module fault | yes |
78
+ | 5 | RS485 fault | yes |
79
+ | 6 | radar and RS485 fault | yes |
80
+
81
+ An undocumented code decodes to `None`, while `status_code` keeps the raw number for diagnostics.
82
+
83
+ > **0.2.0 is a breaking release**: `OK` and `SELF_TEST_FAILED` swapped values, because 0.1.0 read
84
+ > the vendor table one row off.
85
+
86
+ ## Errors
87
+
88
+ The library raises whatever `modbus-connection` raises: a timeout, a protocol error, or a
89
+ refusal of the addressed registers. It does not wrap them, so the caller can tell a dead link
90
+ from a slow device.
91
+
92
+ ## Supported firmware
93
+
94
+ Written against the vendor documentation for firmware **1.6**. The register map is in
95
+ `openspec/specs/mtdx62-registers/` once the first change is archived, and the raw facts are in
96
+ `references/mtdx62/DEVICE-FACTS.md` in the project workspace.
97
+
98
+ ## Tests
99
+
100
+ Tests run against the in-memory backend of `modbus-connection`, so they need neither hardware
101
+ nor Home Assistant:
102
+
103
+ ```bash
104
+ pip install -e ".[test]"
105
+ pytest
106
+ ```
107
+
108
+ ## Author
109
+
110
+ Sergey Astakhov — [sergeyastakhov@mail.ru](mailto:sergeyastakhov@mail.ru),
111
+ [github.com/sergeyastakhov](https://github.com/sergeyastakhov).
112
+
113
+ Source and issues: <https://github.com/sergeyastakhov/mtdx62-modbus-library>. MIT licensed.
@@ -0,0 +1,158 @@
1
+ # Design
2
+
3
+ ## Context
4
+
5
+ Требования — в `specs/mtdx62-registers/spec.md`, мотивация — в `proposal.md`. Исходные данные о
6
+ протоколе — `references/mtdx62/DEVICE-FACTS.md` в корне рабочего пространства.
7
+
8
+ Ограничения, которые задают устройство библиотеки:
9
+
10
+ - `modbus-connection` уже умеет всё, что нужно на уровне обмена: соединение, юниты, блочные
11
+ чтения, повторы, бэкенды `tmodbus` и `pymodbus`. Библиотеке остаётся только карта регистров.
12
+ - Входные и holding-регистры — разные адресные пространства, планировщик не смешивает их в
13
+ одном запросе.
14
+ - Модель обязана работать без Home Assistant, иначе тесты потребуют установленного Home Assistant
15
+ и потеряют смысл.
16
+
17
+ ## Goals / Non-Goals
18
+
19
+ **Goals**
20
+
21
+ - Один файл с картой регистров, который читается как даташит.
22
+ - Один запрос на опрос измерений.
23
+ - Тестируемость без железа: mock-бэкенд `modbus-connection`.
24
+
25
+ **Non-Goals**
26
+
27
+ - Запись параметров устройства.
28
+ - Активный отчёт устройства и подписка на события.
29
+ - Транспорт, повторы, таймауты — зона `modbus-connection`.
30
+ - Интерпретация порога освещённости как логики автоматизации: библиотека отдаёт числа.
31
+
32
+ ## Decisions
33
+
34
+ ### Решение 1: две подсистемы вместо одной плоской модели
35
+
36
+ `readings` описывает входные регистры, `settings` — holding-регистры. У каждой подсистемы свой
37
+ метод обновления.
38
+
39
+ **Почему.** Входные регистры меняются постоянно и читаются каждые 5 секунд, параметры меняются
40
+ редко и нужны только при разборе проблем. Разделение даёт правильную стоимость опроса: чтение
41
+ измерений — один запрос, параметры не читаются вовсе, пока их не попросят. Плоская модель
42
+ заставила бы либо читать всё вместе (два запроса на каждый опрос), либо прятать фильтрацию
43
+ внутри библиотеки.
44
+
45
+ **Альтернативы.** Один компонент на все регистры — лишние запросы при опросе. Отдельные
46
+ компоненты на каждое измерение — восемь запросов вместо одного.
47
+
48
+ ### Решение 2: декларативные поля `modbus_connection.model`
49
+
50
+ Поля описываются готовыми хелперами: `boolean` для присутствия, `integer` для освещённости,
51
+ `gauge(0.01)` для расстояния, `raw_register` для кода состояния, `uint32` для сырых версий.
52
+ Пространство задаётся `register_space = "input"` у компонента измерений.
53
+
54
+ **Почему.** Планировщик сам складывает соседние адреса в один блок, а `boolean` и `uint32`
55
+ уже правильно разбирают крайние случаи (значение вне 0/1, порядок слов). Свой разбор пришлось бы
56
+ писать и тестировать отдельно, и он разошёлся бы с поведением остальных Modbus-интеграций.
57
+
58
+ **Альтернативы.** Ручной разбор байтов — дублирует библиотеку и теряет блочные чтения.
59
+
60
+ ### Решение 3: версии и состояние — производные свойства, а не поля
61
+
62
+ `app_version`, `radar_version` и `status` — свойства поверх сырых полей. Сырые значения остаются
63
+ доступными.
64
+
65
+ **Почему.** Версия склеивается из двух регистров нестандартным образом (байты `0x00010203` = 1.2.3),
66
+ а код состояния может прийти неизвестным. Если бы это были поля, пришлось бы выбирать между
67
+ потерей исходного значения и разбором внутри декодера. Свойства дают и то и другое, а вызывающая
68
+ сторона сама решает, как показать «код неизвестен».
69
+
70
+ **Альтернативы.** Разбор в `convert` поля — неизвестный код превратился бы в `None` без остатка,
71
+ и диагностика потеряла бы исходное число.
72
+
73
+ ### Решение 4: `distance` в метрах, шаг сантиметр
74
+
75
+ Поле объявляется как `gauge(0x0002, 0.01, unit="m")`, то есть значение в метрах с точностью до
76
+ сантиметра.
77
+
78
+ **Почему.** Регистр хранит сантиметры, но метры — единица, в которой расстояние осмысленно в
79
+ интерфейсе и в документации. Преобразование в сантиметры для показа делает интеграция, где
80
+ требуется целое число; здесь важно не терять точность.
81
+
82
+ ### Решение 5: никаких собственных исключений
83
+
84
+ Библиотека не вводит свою иерархию ошибок: таймаут, ошибка протокола и отказ устройства приходят
85
+ из `modbus-connection`.
86
+
87
+ **Почему.** Своя обёртка заставила бы интеграцию разбирать два набора исключений, а различие
88
+ «таймаут» и «ошибка протокола» уже есть на уровне соединения. Единственное, что добавляет
89
+ библиотека, — ничего не глотает.
90
+
91
+ ## Data Model
92
+
93
+ Постоянного хранилища нет: значения живут в атрибутах подсистем, пока объект устройства жив.
94
+
95
+ Карта регистров (полностью — в `references/mtdx62/DEVICE-FACTS.md`):
96
+
97
+ | Подсистема | Атрибут | Адрес | Поле модели |
98
+ |---|---|---|---|
99
+ | `readings` | `presence` | input `0x0000` | `boolean` |
100
+ | `readings` | `illuminance` | input `0x0001` | `integer`, ед. лк |
101
+ | `readings` | `distance` | input `0x0002` | `gauge`, шаг 0.01, ед. м |
102
+ | `readings` | `status_code` | input `0x0003` | `raw_register` |
103
+ | `readings` | `app_version_raw` | input `0x0004…0x0005` | `uint32` |
104
+ | `readings` | `radar_version_raw` | input `0x0006…0x0007` | `uint32` |
105
+ | `settings` | `detection_distance` | holding `0x0000` | `gauge`, шаг 0.01, ед. м |
106
+ | `settings` | `shielding_distance` | holding `0x0001` | `gauge`, шаг 0.01, ед. м |
107
+ | `settings` | `entry_delay` | holding `0x0002` | `gauge`, шаг 0.01, ед. с |
108
+ | `settings` | `departure_delay` | holding `0x0003` | `integer`, ед. с |
109
+ | `settings` | `trigger_sensitivity` | holding `0x0004` | `integer` |
110
+ | `settings` | `maintain_sensitivity` | holding `0x0005` | `integer` |
111
+ | `settings` | `entry_indent` | holding `0x0006` | `gauge`, шаг 0.01, ед. м |
112
+ | `settings` | `unit_id` | holding `0x0007` | `integer` |
113
+ | `settings` | `baudrate` | holding `0x0008` | `integer`, ед. бод |
114
+ | `settings` | `parity` | holding `0x0009` | `integer` |
115
+ | `settings` | `active_report` | holding `0x000A` | `integer` |
116
+ | `settings` | `light_threshold` | holding `0x000B` | `gauge`, шаг 0.01, ед. лк |
117
+ | `settings` | `report_interval` | holding `0x000C` | `integer`, ед. с |
118
+
119
+ Принадлежность `0x000B` и `0x000C` в документации противоречива — это открытый вопрос, который
120
+ проверяется на живом устройстве. На поведение библиотеки он не влияет: оба поля только читаются
121
+ для диагностики.
122
+
123
+ ## Rule Boundary
124
+
125
+ Изменение не вводит бизнес-правил, проверок и новых путей исполнения: библиотека только читает
126
+ регистры и декодирует значения. Валидация адресов и параметров связи остаётся в интеграции, где
127
+ есть пользовательский ввод.
128
+
129
+ ## Interface & Implementation Mapping
130
+
131
+ Не применимо: у библиотеки нет пользовательского интерфейса, её интерфейс — публичный API пакета,
132
+ описанный в спецификации.
133
+
134
+ ## Risks / Trade-offs
135
+
136
+ - **Зависимость от `modbus-connection`** → библиотека следует за её версиями; ломающая правка
137
+ контракта требует мажорной версии и обновления интеграции. Снимается тем, что версия
138
+ фиксируется точно в `pyproject.toml`.
139
+ - **Неизвестный код состояния превращается в `None`** → интеграция обязана показать «код
140
+ неизвестен», а не пустоту. Снимается тем, что `status_code` остаётся доступным.
141
+ - **Параметры читаются по требованию** → первый вызов диагностики будет медленнее (лишний
142
+ запрос). Приемлемо: диагностика вызывается вручную.
143
+ - **Порог освещённости не используется** → поле читается, но не влияет на присутствие: логика
144
+ порога живёт в устройстве. Снимается тем, что библиотека не претендует на эту логику.
145
+
146
+ ## Migration Plan
147
+
148
+ Пакет новый, миграций нет. Публикация: `0.1.0` на PyPI, затем интеграция фиксирует
149
+ `mtdx62==0.1.0` в манифесте. Откат — снятие версии с PyPI и откат зависимости в интеграции.
150
+
151
+ ## Open Questions
152
+
153
+ 1. **Адреса `0x000B` и `0x000C`.** Примеры кадров в сканах противоречат друг другу: и порог
154
+ освещённости, и интервал отчёта показаны по адресу `0x000B`. Проверка на живом устройстве:
155
+ изменить порог пультом и посмотреть, какой регистр сдвинулся. До проверки поля остаются как
156
+ в таблице, но в интеграцию не выводятся.
157
+ 2. **Код MAC в `0x000D`.** В одном примере чтение MAC идёт по адресу `0x000C`. В эту версию не
158
+ входит; понадобится, если интеграция перейдёт на идентификатор по MAC.
@@ -0,0 +1,48 @@
1
+ # Proposal
2
+
3
+ ## Why
4
+
5
+ Датчик отдаёт наружу десять регистров, которые нужно читать правильно: у каждого свой
6
+ масштаб, часть значений склеена из двух регистров, а код состояния — числовой код с шестью
7
+ известными значениями. Если разбирать это прямо в интеграции Home Assistant, то проверить
8
+ разбор можно будет только через Home Assistant и только с железом.
9
+
10
+ Библиотека `mtdx62` переносит карту регистров в отдельный пакет: его можно тестировать на
11
+ mock-бэкенде без датчика и без Home Assistant, а интеграция получает типизированный объект
12
+ устройства и не знает числовых адресов.
13
+
14
+ ## What Changes
15
+
16
+ - Появляется пакет `mtdx62` на PyPI, построенный на `modbus-connection`.
17
+ - Верхний объект `Mtdx62Device` принимает `ModbusUnit` и отдаёт две подсистемы:
18
+ - `readings` — измерения из входных регистров: присутствие, освещённость, расстояние,
19
+ код состояния, версии приложения и радара;
20
+ - `settings` — параметры устройства из holding-регистров, только для чтения.
21
+ - Разбор значений: расстояние в метрах с шагом 0.01, освещённость в люксах, версии собираются
22
+ из двух регистров в строку `1.2.3`, код состояния переводится в перечисление с отдельным
23
+ исходом «код неизвестен».
24
+ - Чтение измерений укладывается в один блочный запрос; параметры читаются отдельным запросом
25
+ только по требованию.
26
+ - Библиотека ничего не пишет в устройство: запись параметров появится отдельным изменением.
27
+ - Библиотека не зависит от Home Assistant и не открывает соединений: соединение даёт
28
+ `modbus-connection`, юнит передаёт вызывающая сторона.
29
+
30
+ ## Capabilities
31
+
32
+ ### New Capabilities
33
+
34
+ - `mtdx62-registers`: карта регистров датчика и её разбор — что библиотека читает, как
35
+ декодирует значения и как ведёт себя, когда устройство молчит или отдаёт неизвестный код.
36
+
37
+ ### Modified Capabilities
38
+
39
+ Нет: это первая библиотека проекта, `openspec/specs/` пока пуст.
40
+
41
+ ## Impact
42
+
43
+ - Новый репозиторий `libraries/mtdx62` (PyPI, MIT), версия `0.1.0`.
44
+ - Зависимости: `modbus-connection[tmodbus]`. Прямой зависимости от `pymodbus`, `pyserial`
45
+ или Home Assistant нет.
46
+ - Потребитель — интеграция `integrations/mtdx62`; при изменении контракта ломается её код,
47
+ поэтому ломающие правки требуют мажорной версии.
48
+ - Тесты идут на mock-бэкенде `modbus-connection`, без железа и без Home Assistant.