eletechsup-modbus-library 0.1.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.
@@ -0,0 +1,12 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ venv/
5
+ .mypy_cache/
6
+ .pytest_cache/
7
+ .ruff_cache/
8
+ .coverage
9
+ htmlcov/
10
+ dist/
11
+ build/
12
+ *.egg-info/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Eletechsup integration developers
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,126 @@
1
+ Metadata-Version: 2.5
2
+ Name: eletechsup-modbus-library
3
+ Version: 0.1.0
4
+ Summary: Async Modbus RTU library for Eletechsup relay, IO, PWM and measurement modules
5
+ Project-URL: Documentation, https://github.com/sergeyastakhov/eletechsup-modbus-library#readme
6
+ Project-URL: Source, https://github.com/sergeyastakhov/eletechsup-modbus-library
7
+ Project-URL: Issues, https://github.com/sergeyastakhov/eletechsup-modbus-library/issues
8
+ Project-URL: Changelog, https://github.com/sergeyastakhov/eletechsup-modbus-library/blob/main/CHANGELOG.md
9
+ Author: Sergey Astakhov
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: asyncio,eletechsup,home-assistant,home-automation,modbus,modbus-connection,modbus-rtu,rs485
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Framework :: AsyncIO
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: Home Automation
20
+ Classifier: Topic :: System :: Hardware
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.14
23
+ Requires-Dist: modbus-connection<5,>=4.12.4
24
+ Provides-Extra: test
25
+ Requires-Dist: mypy>=1.19; extra == 'test'
26
+ Requires-Dist: pytest-asyncio>=1.2; extra == 'test'
27
+ Requires-Dist: pytest-cov>=7; extra == 'test'
28
+ Requires-Dist: pytest>=9; extra == 'test'
29
+ Requires-Dist: ruff>=0.14; extra == 'test'
30
+ Description-Content-Type: text/markdown
31
+
32
+ # eletechsup-modbus-library
33
+
34
+ Async Modbus RTU protocol library for Eletechsup modules. It owns the register map, the value
35
+ decoding and the write rules; it does not own the transport and does not depend on Home Assistant.
36
+
37
+ The first supported family is **10IOAXX** — industrial IO modules with N opto-isolated inputs and N
38
+ relays on RS485. Profiles for the models are the only place that describes the hardware, so a new
39
+ family is added by registering profiles and components rather than by editing existing ones.
40
+
41
+ ## Installation
42
+
43
+ ```bash
44
+ pip install eletechsup-modbus-library
45
+ ```
46
+
47
+ Python 3.14 or newer is required. The library builds on
48
+ [`modbus-connection`](https://pypi.org/project/modbus-connection/) and passes its tests on the
49
+ in-memory backend shipped with it.
50
+
51
+ ## Usage
52
+
53
+ The caller owns the Modbus unit — a serial port, a TCP gateway, or the Home Assistant `modbus`
54
+ integration. The library never opens or closes a connection.
55
+
56
+ ```python
57
+ from eletechsup_modbus_library import EletechsupDevice, RelationMode, require_profile
58
+
59
+ device = EletechsupDevice(unit, require_profile("10IOA04"))
60
+
61
+ await device.async_update_state()
62
+ first_relay = device.digital_output(0)
63
+
64
+ await device.async_set_digital_output(0, on=True)
65
+ await device.async_set_relation(RelationMode.INTERLOCKING_PAIR)
66
+ ```
67
+
68
+ Reading is split on purpose: `async_update_state()` is two single-register reads of the output and
69
+ input masks, `async_update_settings()` is one request for the settings block. A slow or unreachable
70
+ device therefore never hides the state that was read successfully.
71
+
72
+ Writing is verified. Every settings write is followed by a read-back, and a device that acknowledges
73
+ a write but keeps another value raises `ValueNotStoredError` instead of pretending success. The only
74
+ exception is the factory reset: after it the device changes speed, parity and address, so a read-back
75
+ would fail for reasons that are not an error.
76
+
77
+ ## Supported devices
78
+
79
+ | Model | Inputs | Relays | Product ID |
80
+ |---|---|---|---|
81
+ | 10IOA01 | 1 | 1 | 1001 |
82
+ | 10IOA02 | 2 | 2 | 1002 |
83
+ | 10IOA04 | 4 | 4 | 1004 |
84
+ | 10IOA08 | 8 | 8 | 1008 |
85
+ | 10IOA12 | 12 | 12 | 1012 |
86
+
87
+ Catalogue articles such as `10IOA0112VR` differ in power supply and enclosure only; the protocol is
88
+ the same, so profiles use the base model name.
89
+
90
+ ## Dependencies
91
+
92
+ The lower bound is `modbus-connection>=4.12.4`. That is the version the `modbus` integration of
93
+ Home Assistant 2026.10 requires in its own manifest, so the library never asks for a newer transport
94
+ than the Home Assistant it is installed into already ships. CI runs the suite twice: against that
95
+ lower bound and against the latest release.
96
+
97
+ ## Protocol notes
98
+
99
+ - Defaults: 9600 baud, 8 data bits, no parity, 1 stop bit. Address 1–63 is set by DIP switches on
100
+ these models, so the address register is read-only.
101
+ - Outputs are read from the holding register `0x0080` and written as single coils; inputs are read
102
+ from `0x0090`. A short input pulse can fall between two polls — the device does not latch it.
103
+ - Changing baud rate or parity is stored immediately but takes effect only after a power cycle.
104
+ - The factory reset (`0x00FB`) is available as a method but is not exposed by the integration.
105
+
106
+ Device facts, the register map and the differences between firmware versions are documented in
107
+ [the library documentation](https://github.com/sergeyastakhov/eletechsup-modbus-library/blob/main/docs/10ioaxx/DEVICE-FACTS.md).
108
+ The cross-family picture is in
109
+ [the family overview](https://github.com/sergeyastakhov/eletechsup-modbus-library/blob/main/docs/FAMILIES.md).
110
+
111
+ ## Development
112
+
113
+ ```bash
114
+ python -m pytest --cov=eletechsup_modbus_library
115
+ ruff format --check .
116
+ ruff check .
117
+ mypy src
118
+ ```
119
+
120
+ The transport is mocked on its boundary with the in-memory backend, so the tests need neither
121
+ hardware nor a serial port. Every OpenSpec scenario of the change has a test; the requirement is
122
+ named in the test module.
123
+
124
+ ## License
125
+
126
+ MIT — see [LICENSE](https://github.com/sergeyastakhov/eletechsup-modbus-library/blob/main/LICENSE).
@@ -0,0 +1,95 @@
1
+ # eletechsup-modbus-library
2
+
3
+ Async Modbus RTU protocol library for Eletechsup modules. It owns the register map, the value
4
+ decoding and the write rules; it does not own the transport and does not depend on Home Assistant.
5
+
6
+ The first supported family is **10IOAXX** — industrial IO modules with N opto-isolated inputs and N
7
+ relays on RS485. Profiles for the models are the only place that describes the hardware, so a new
8
+ family is added by registering profiles and components rather than by editing existing ones.
9
+
10
+ ## Installation
11
+
12
+ ```bash
13
+ pip install eletechsup-modbus-library
14
+ ```
15
+
16
+ Python 3.14 or newer is required. The library builds on
17
+ [`modbus-connection`](https://pypi.org/project/modbus-connection/) and passes its tests on the
18
+ in-memory backend shipped with it.
19
+
20
+ ## Usage
21
+
22
+ The caller owns the Modbus unit — a serial port, a TCP gateway, or the Home Assistant `modbus`
23
+ integration. The library never opens or closes a connection.
24
+
25
+ ```python
26
+ from eletechsup_modbus_library import EletechsupDevice, RelationMode, require_profile
27
+
28
+ device = EletechsupDevice(unit, require_profile("10IOA04"))
29
+
30
+ await device.async_update_state()
31
+ first_relay = device.digital_output(0)
32
+
33
+ await device.async_set_digital_output(0, on=True)
34
+ await device.async_set_relation(RelationMode.INTERLOCKING_PAIR)
35
+ ```
36
+
37
+ Reading is split on purpose: `async_update_state()` is two single-register reads of the output and
38
+ input masks, `async_update_settings()` is one request for the settings block. A slow or unreachable
39
+ device therefore never hides the state that was read successfully.
40
+
41
+ Writing is verified. Every settings write is followed by a read-back, and a device that acknowledges
42
+ a write but keeps another value raises `ValueNotStoredError` instead of pretending success. The only
43
+ exception is the factory reset: after it the device changes speed, parity and address, so a read-back
44
+ would fail for reasons that are not an error.
45
+
46
+ ## Supported devices
47
+
48
+ | Model | Inputs | Relays | Product ID |
49
+ |---|---|---|---|
50
+ | 10IOA01 | 1 | 1 | 1001 |
51
+ | 10IOA02 | 2 | 2 | 1002 |
52
+ | 10IOA04 | 4 | 4 | 1004 |
53
+ | 10IOA08 | 8 | 8 | 1008 |
54
+ | 10IOA12 | 12 | 12 | 1012 |
55
+
56
+ Catalogue articles such as `10IOA0112VR` differ in power supply and enclosure only; the protocol is
57
+ the same, so profiles use the base model name.
58
+
59
+ ## Dependencies
60
+
61
+ The lower bound is `modbus-connection>=4.12.4`. That is the version the `modbus` integration of
62
+ Home Assistant 2026.10 requires in its own manifest, so the library never asks for a newer transport
63
+ than the Home Assistant it is installed into already ships. CI runs the suite twice: against that
64
+ lower bound and against the latest release.
65
+
66
+ ## Protocol notes
67
+
68
+ - Defaults: 9600 baud, 8 data bits, no parity, 1 stop bit. Address 1–63 is set by DIP switches on
69
+ these models, so the address register is read-only.
70
+ - Outputs are read from the holding register `0x0080` and written as single coils; inputs are read
71
+ from `0x0090`. A short input pulse can fall between two polls — the device does not latch it.
72
+ - Changing baud rate or parity is stored immediately but takes effect only after a power cycle.
73
+ - The factory reset (`0x00FB`) is available as a method but is not exposed by the integration.
74
+
75
+ Device facts, the register map and the differences between firmware versions are documented in
76
+ [the library documentation](https://github.com/sergeyastakhov/eletechsup-modbus-library/blob/main/docs/10ioaxx/DEVICE-FACTS.md).
77
+ The cross-family picture is in
78
+ [the family overview](https://github.com/sergeyastakhov/eletechsup-modbus-library/blob/main/docs/FAMILIES.md).
79
+
80
+ ## Development
81
+
82
+ ```bash
83
+ python -m pytest --cov=eletechsup_modbus_library
84
+ ruff format --check .
85
+ ruff check .
86
+ mypy src
87
+ ```
88
+
89
+ The transport is mocked on its boundary with the in-memory backend, so the tests need neither
90
+ hardware nor a serial port. Every OpenSpec scenario of the change has a test; the requirement is
91
+ named in the test module.
92
+
93
+ ## License
94
+
95
+ MIT — see [LICENSE](https://github.com/sergeyastakhov/eletechsup-modbus-library/blob/main/LICENSE).
@@ -0,0 +1,111 @@
1
+ # Скрипты живой проверки протокола
2
+
3
+ Скрипты, которыми получены измерения из `../DEVICE-FACTS.md`. История опытов, промежуточные и
4
+ опровергнутые выводы — в `../RESEARCH-LOG.md`. Они говорят напрямую с
5
+ модулем по RS485 через pyserial, без Home Assistant и без стека `modbus-connection`: так видно голые
6
+ кадры и тайминги, а не поведение библиотеки.
7
+
8
+ **Осторожно: часть скриптов пишет в устройство.** `probe4.py` меняет скорость, чётность и адрес,
9
+ `probe5.py` — задержку ответа и регистры связи, `probe2.py`, `probe3.py`, `probe6.py`, `probe7.py` —
10
+ состояние реле и автоотчёт. Все они восстанавливают исходные значения и печатают итоговое состояние,
11
+ но запускать их на устройстве, которое уже используется в щитке, не нужно. Для проверки нового модуля
12
+ возьмите отдельную плату на столе.
13
+
14
+ ## Что чем проверялось
15
+
16
+ | Скрипт | Что делает | Пишет в устройство |
17
+ |---|---|---|
18
+ | `probe.py` | первичный осмотр: Product ID, блок настроек, маски, обе карты, чтение адресов вне карты | нет |
19
+ | `probe2.py` | время отклика, темп опроса, запись реле (FC05), режим связи, адрес, автоотчёт | да, восстанавливает |
20
+ | `probe3.py` | длительная нагрузка, сверка катушек и регистровых масок, помехи от автоотчёта | да, восстанавливает |
21
+ | `probe4.py` | задержка ответа, скорость, чётность, адрес: сохраняется ли и когда действует | да, восстанавливает |
22
+ | `probe5.py` | закон задержки ответа, чтение после записи, порядок бит в катушках | да, восстанавливает |
23
+ | `probe6.py` | смешанный обмен, опыт с недОчитанным ответом, тишина без автоотчёта | да, восстанавливает |
24
+ | `probe7.py` | частота отказов по типу обмена и по паузе между запросами | да, восстанавливает |
25
+ | `check_baud_readback.py` | сохраняется ли код скорости, пока обмен идёт на прежней | да, восстанавливает |
26
+ | `probe_reset.py` | снимок состояния после аппаратного сброса, команда сброса по обычному адресу | да, сбрасывает |
27
+ | `probe_reset2.py` | сбрасывает регистры в нестандартные значения и проверяет, что команда сброса вернула заводские | да, сбрасывает |
28
+ | `probe_pulse.py` | режимы 0x0000, 0x0001, 0x0003, 0x0005: что делает импульс на DI1, длительность «хвоста» | да, восстанавливает сбросом |
29
+ | `arm_powercycle.py` | записывает 19200/Odd для проверки перезапуска питания, обмен пока идёт на 9600/N | да |
30
+ | `verify_powercycle.py` | после перезапуска питания ищет модуль по четырём сочетаниям и делает сброс | да, сбрасывает |
31
+ | `probe_softdi.py` | попытка подать сигнал на вход программно: запись в `0x0090`, в резервный `0x00F9`, в катушки сверх числа реле, поведение режимов при этом | да, сбрасывает |
32
+ | `probe_softdi2.py` | то же другими способами (FC16 в `0x0090`, катушки 8–11) — подтверждает, что вход только для чтения | да, сбрасывает |
33
+ | `probe_writes.py` | как устройство относится к записи вне карты регистров: эхо и игнорирование внутри 0x0000–0x00FF, исключение 02 с 0x0100 | да, меняет чётность и возвращает |
34
+ | `probe_interlock.py` | режимы 0x0002 и 0x0004 через перемычку «реле 5 → IN5»: генератор импульсов на входе — сама команда записи реле | да, сбрасывает |
35
+ | `probe_momentary.py` | режим 0x0003 через перемычку «реле 5 → IN4»: длительность одновибратора при разном удержании входа | да, сбрасывает |
36
+ | `probe_momentary2.py` | режим 0x0003: перезапуск по фронту (два импульса через 600 и 200 мс) и минимальная ловимая длительность | да, сбрасывает |
37
+ | `probe_momentary3.py` | команда включения реле в режиме 0x0003, защёлкивание короткого импульса на входе | да, сбрасывает |
38
+ | `final_state.py` | печатает состояние всех регистров — чем заканчивать проверку | нет |
39
+
40
+ `probe_pulse.py`, `arm_powercycle.py` и `verify_powercycle.py` требуют человека: первый — замыкать вход,
41
+ второй и третий — перезапускать питание между запусками.
42
+
43
+ ## Диагностика шины с несколькими модулями
44
+
45
+ | Скрипт | Что делает |
46
+ |---|---|
47
+ | `probe_scan.py` | перебирает адреса 1–63 с коротким таймаутом и печатает, кто где отвечает |
48
+ | `probe_scan_slow.py` | то же с длинным таймаутом: не пропускает медленные модули (у них ответ 110–120 мс) |
49
+ | `probe_fingerprint.py` | отпечаток одного модуля по адресу: текущие и заводские значения, поведенческие маркеры; выключает автоотчёт и делает сброс |
50
+ | `probe_bus_health.py` | по 100 чтений на адрес: доля ошибок и среднее время ответа |
51
+ | `probe_unit4.py` | подробное сравнение подозрительного адреса с контрольным |
52
+ | `probe_raw.py` | сырой дамп: все байты ответа с межбайтовыми интервалами |
53
+ | `probe_frames.py` | сколько законных кадров приходит на один запрос |
54
+ | `probe_map.py` | карта «какой адрес кто отвечает», включая ответы с чужим адресом в кадре |
55
+ | `probe_stray.py` | проверка, отвечает ли кто-то на широковещательный и несуществующие адреса |
56
+ | `probe_rogue2.py` | характеризация модуля, который отвечает на любой адрес: доля ответов и задержки |
57
+ | `probe_gap.py` | частота ошибок в зависимости от паузы между транзакциями |
58
+ | `probe_mixedlog.py` | подробный журнал смешанного опроса: каждый запрос, время, ошибка, кадр |
59
+ | `probe_findall.py` | поиск модулей по всем скоростям и чётностям на адресах 1–16 |
60
+ | `probe_autoreport.py` | состояние автоотчёта и настроек по всем адресам |
61
+ | `probe_listen.py` | пассивное слушание шины и повторный опрос адресов |
62
+ | `probe_com5.py` | проверка второго адаптера и адреса 3 с длинным таймаутом |
63
+ | `probe_reliability.py`, `probe_reliability2.py` | надёжность по адресам и смешанный опрос |
64
+ | `probe_reset_clean.py` | сброс без включения автоотчёта: сравнение быстрой и медленной прошивки |
65
+ | `probe_mod3.py` | обращение к «пропавшему» модулю первым кадром, затем по одному соседу перед ним |
66
+ | `probe_hang.py` | переживает ли модуль полное сканирование адресов |
67
+ | `probe_recover.py` | оживает ли замолчавший модуль сам, без перезапуска питания |
68
+ | `probe_mod4_resilience.py` | выдерживает ли второй модуль той же прошивки серии запросов к соседям |
69
+ | `probe_reliability5.py` | надёжность и смешанный опрос всех пяти адресов |
70
+ | `probe_hang2.py` | воспроизведение зависания модуля 3 на другом блоке питания |
71
+ | `probe_mod4_load.py` | контрольный опыт: модуль той же прошивки под 900 запросами к соседям |
72
+ | `probe_staircase.py` | сколько чужих кадров выдерживает модуль, прежде чем замолчать |
73
+ | `probe_swap.py`, `probe_swap2.py` | A/B-опыты после перестановки модулей и переключателей адреса |
74
+ | `probe_addr3.py` | кто где по времени ответа и кто выживает под нагрузкой (после обмена адресами 3 и 5) |
75
+ | `probe_3raw.py`, `probe_3long.py` | что именно приходит от адреса 3: сырые байты и длинный таймаут |
76
+ | `probe_final_reliability.py` | итоговая надёжность четырёх модулей на общей шине |
77
+
78
+ Эти скрипты понадобились, когда на шине оказался модуль с неисправными переключателями адреса: он
79
+ отвечает на любой адрес с задержкой до секунды и ломает обмен всем остальным. Симптомы в интерфейсе —
80
+ ошибки CRC и «ответ не на тот запрос», а не «устройство молчит».
81
+
82
+ ## Две ловушки, на которых я потерял время
83
+
84
+ **Межкадровая пауза.** Скрипты сначала отправляли следующий кадр сразу после ответа. На одиночном
85
+ модуле это почти не мешало (0.05 % ошибок), а на шине из четырёх модулей давало 36 % ошибок. С паузой
86
+ 5 мс — ноль. Это обычные 3.5 символа тишины Modbus RTU (около 4 мс на 9600 бод). В `probe.py` и
87
+ `probe2.py` пауза уже встроена; если пишете свой скрипт — добавьте её сами.
88
+
89
+ **Автоотчёт.** `probe_fingerprint.py` включает автоотчёт (`0x00F8 = 3`) в проверке поведения. На
90
+ прошивке, где команда сброса не работает, автоотчёт остаётся включённым: модуль мигает светодиодом
91
+ передачи и шлёт кадры вида `04 03 02 00 00 …`, которые легко принять за «модуль отвечает на чужие
92
+ адреса». Поэтому скрипт выключает автоотчёт явно, записью нуля, и печатает `auto_report_after_probe`.
93
+
94
+ ## Запуск
95
+
96
+ Нужен Python 3.14 и `pyserial`. Скрипты импортируют друг друга, поэтому запускать из этой папки:
97
+
98
+ ```
99
+ python probe.py COM6
100
+ python probe2.py COM6
101
+ ```
102
+
103
+ Порт, скорость и параметры по умолчанию — 9600, 8 бит, без чётности, 1 стоп-бит; адрес модуля — 1.
104
+ В скриптах адрес задан константой `UNIT`, при другом адресе её нужно поменять.
105
+
106
+ ## Что делать, если модуль перестал отвечать
107
+
108
+ `probe4.py` при потере связи перебирает скорости и чётности, пока не найдёт модуль, и восстанавливает
109
+ исходные значения. Если и это не помогло, значит устройство применило сохранённые параметры: включите
110
+ и выключите питание, затем повторите запуск с параметрами, которые были записаны, и верните исходные
111
+ значения.
@@ -0,0 +1,52 @@
1
+ # Документация библиотеки
2
+
3
+ Здесь живёт всё, что описывает устройства, с которыми работает библиотека. Документация разложена по
4
+ семействам: у каждого семейства свой каталог, потому что семейства добавляются независимо и не должны
5
+ мешать друг другу.
6
+
7
+ ```
8
+ docs/
9
+ ├── README.md # этот файл: как устроена документация
10
+ └── 10ioaxx/ # семейство «N входов + N реле на RS485»
11
+ ├── DEVICE-FACTS.md # факты: документация, расхождения, недокументированные особенности, прошивки
12
+ ├── RESEARCH-LOG.md # история исследований: опыты, промежуточные и опровергнутые выводы
13
+ ├── sources/ # материалы производителя как есть (docx, архивы)
14
+ ├── extracted-text/ # распознанный текст материалов
15
+ ├── images/ # фотографии и схемы из руководств
16
+ └── probes/ # скрипты живой проверки протокола
17
+ ```
18
+
19
+ ## Правила
20
+
21
+ - **`DEVICE-FACTS.md` — только факты.** Что говорит производитель, что подтверждено на железе, где
22
+ документация расходится с устройством, какие особенности не описаны, какие варианты прошивок
23
+ встретились и чем они отличаются. Никакой истории, никаких «сначала думали так».
24
+ - **`RESEARCH-LOG.md` — история.** Что и зачем проверяли, какими кадрами, какие выводы делали по ходу,
25
+ какие из них не подтвердились и почему. Сюда же — состояние стенда и что осталось непроверенным.
26
+ - **Новое семейство — новый каталог.** `docs/<family>/` с теми же именами файлов. Семейство
27
+ определяется протоколом и раскладкой регистров, а не каталожным артикулом: модели одного семейства
28
+ отличаются числом каналов, но не картой.
29
+ - **Ссылки на факты — относительные.** Спецификации, дизайн и задачи ссылаются на
30
+ `docs/<family>/DEVICE-FACTS.md` с указанием семейства, чтобы при добавлении второго семейства не
31
+ пришлось править формулировки.
32
+ - **Материалы производителя не переписываются.** Распознанный текст и производные документы лежат
33
+ отдельно от исходников.
34
+
35
+ ## Текущие семейства
36
+
37
+ | Каталог | Семейство | Состояние |
38
+ |---|---|---|
39
+ | `10ioaxx/` | 10IOA01, 02, 04, 08, 12 — N входов + N реле | проверено на живых модулях |
40
+ | `ryr/` | RYR404A, 408B, 416C, 432D — 4/8/16/32 реле, без входов | только документация |
41
+ | `25io/` | 25IOA08, B16, C32 — 8/16/32 канала, два набора команд по джамперу M0 | только документация |
42
+ | `r4d7g04/` | R4D7G04 — 4 реле, 2 дискретных и 3 аналоговых входа | только документация |
43
+ | `n4aia/` | N4AIA08, B16, C24 — 8/16/24 аналоговых входа (ток, напряжение) | только документация |
44
+ | `n4via02/` | N4VIA02 — 2 канала измерения тока и напряжения | только документация |
45
+ | `n43vd04/` | N43VD04 — 4 канала измерения напряжения | только документация |
46
+ | `pta9b01/` | PTA9B01 — 1 канал PT100, ранняя компактная карта | только документация |
47
+ | `pt21a01/` | PT21A01, PT22B01 — 1 канал PT100 | только документация |
48
+ | `ptdnc04/` | PTDNC04 — 4 канала PT100/PT1000 | только документация |
49
+ | `pwm8a04/` | PWM8A04 — 3 канала PWM: частота и скважность на канал | только документация |
50
+
51
+ Общая картина по семействам — что между ними общего и что различается, как из этого складывается
52
+ библиотека — в [`FAMILIES.md`](FAMILIES.md).
@@ -0,0 +1,105 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "eletechsup-modbus-library"
7
+ version = "0.1.0"
8
+ description = "Async Modbus RTU library for Eletechsup relay, IO, PWM and measurement modules"
9
+ readme = "README.md"
10
+ requires-python = ">=3.14"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Sergey Astakhov" }]
14
+ keywords = [
15
+ "modbus",
16
+ "modbus-rtu",
17
+ "rs485",
18
+ "modbus-connection",
19
+ "home-assistant",
20
+ "home-automation",
21
+ "eletechsup",
22
+ "asyncio",
23
+ ]
24
+ classifiers = [
25
+ "Development Status :: 4 - Beta",
26
+ "Framework :: AsyncIO",
27
+ "Intended Audience :: Developers",
28
+ "Operating System :: OS Independent",
29
+ "Programming Language :: Python :: 3",
30
+ "Programming Language :: Python :: 3.14",
31
+ "Topic :: Home Automation",
32
+ "Topic :: System :: Hardware",
33
+ "Typing :: Typed",
34
+ ]
35
+ dependencies = ["modbus-connection>=4.12.4,<5"]
36
+
37
+ [project.optional-dependencies]
38
+ test = [
39
+ "mypy>=1.19",
40
+ "pytest>=9",
41
+ "pytest-asyncio>=1.2",
42
+ "pytest-cov>=7",
43
+ "ruff>=0.14",
44
+ ]
45
+
46
+ [project.urls]
47
+ Documentation = "https://github.com/sergeyastakhov/eletechsup-modbus-library#readme"
48
+ Source = "https://github.com/sergeyastakhov/eletechsup-modbus-library"
49
+ Issues = "https://github.com/sergeyastakhov/eletechsup-modbus-library/issues"
50
+ Changelog = "https://github.com/sergeyastakhov/eletechsup-modbus-library/blob/main/CHANGELOG.md"
51
+
52
+ [tool.hatch.build.targets.wheel]
53
+ packages = ["src/eletechsup_modbus_library"]
54
+
55
+ [tool.hatch.build.targets.sdist]
56
+ include = ["src/eletechsup_modbus_library", "tests", "README.md", "LICENSE"]
57
+
58
+ [tool.pytest.ini_options]
59
+ asyncio_mode = "auto"
60
+ testpaths = ["tests"]
61
+ addopts = "-q --strict-markers"
62
+
63
+ [tool.coverage.run]
64
+ branch = true
65
+ source = ["eletechsup_modbus_library"]
66
+
67
+ [tool.coverage.report]
68
+ fail_under = 95
69
+ show_missing = true
70
+
71
+ [tool.ruff]
72
+ line-length = 100
73
+ target-version = "py314"
74
+ extend-exclude = ["docs", "build", "dist"]
75
+
76
+ [tool.ruff.lint]
77
+ select = ["ALL"]
78
+ ignore = [
79
+ "D203", # конфликтует с D211
80
+ "D213", # конфликтует с D212
81
+ "COM812", # конфликтует с formatter
82
+ "ISC001", # конфликтует с formatter
83
+ "CPY001", # заголовок об авторских правах в этих файлах не ведётся
84
+ "ANN401", # валидаторы полей принимают Any по контракту modbus-connection
85
+ "TRY004", # транспорт ждёт ValueError от валидатора
86
+ "EM101", # короткие сообщения об ошибках читаются лучше констант
87
+ "TRY003",
88
+ ]
89
+
90
+ [tool.ruff.lint.per-file-ignores]
91
+ "tests/*" = ["ANN", "S101", "PLR2004", "D103", "INP001", "SLF001", "FBT", "ARG"]
92
+ "scripts/*" = ["INP001", "T201"]
93
+
94
+ [tool.ruff.lint.pydocstyle]
95
+ convention = "google"
96
+
97
+ [tool.mypy]
98
+ python_version = "3.14"
99
+ strict = true
100
+ files = ["src"]
101
+ warn_unreachable = true
102
+
103
+ [[tool.mypy.overrides]]
104
+ module = "tests.*"
105
+ disallow_untyped_defs = false
@@ -0,0 +1,109 @@
1
+ """Modbus RTU protocol library for Eletechsup modules."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Final
6
+
7
+ from .const import (
8
+ BAUDRATE_CODES,
9
+ BAUDRATES,
10
+ COIL_OUTPUT_START,
11
+ DEFAULT_PARITY_CODES,
12
+ FAMILY_10IOAXX,
13
+ HOLDING_ADDRESS,
14
+ HOLDING_AUTO_REPORT,
15
+ HOLDING_BAUDRATE,
16
+ HOLDING_FACTORY_RESET,
17
+ HOLDING_INPUTS,
18
+ HOLDING_OUTPUTS,
19
+ HOLDING_PARITY,
20
+ HOLDING_PRODUCT_ID,
21
+ HOLDING_RELATION,
22
+ HOLDING_RETURN_TIME,
23
+ HOLDING_SETTINGS_COUNT,
24
+ HOLDING_SETTINGS_START,
25
+ MANUFACTURER,
26
+ MAX_ADDRESS,
27
+ MAX_AUTO_REPORT_SECONDS,
28
+ MAX_RETURN_TIME_MS,
29
+ MIN_ADDRESS,
30
+ CorrectionKind,
31
+ Parity,
32
+ RelationMode,
33
+ )
34
+ from .device import EletechsupDevice, SettingsSnapshot
35
+ from .errors import (
36
+ ChannelOutOfRangeError,
37
+ EletechsupError,
38
+ UnknownFamilyError,
39
+ UnknownLayoutError,
40
+ UnknownModelError,
41
+ UnknownVariantError,
42
+ ValueNotStoredError,
43
+ ValueOutOfRangeError,
44
+ )
45
+ from .layouts import Layout, MaskRegistersLayout
46
+ from .profiles import AnalogChannel, DeviceProfile
47
+ from .registry import (
48
+ PROFILES,
49
+ build_registry,
50
+ families,
51
+ profile_for_model,
52
+ profile_for_model_in_family,
53
+ profile_for_product_id,
54
+ profiles_for_family,
55
+ require_profile,
56
+ )
57
+
58
+ __version__: Final = "0.1.0"
59
+
60
+ __all__ = [
61
+ "BAUDRATES",
62
+ "BAUDRATE_CODES",
63
+ "COIL_OUTPUT_START",
64
+ "DEFAULT_PARITY_CODES",
65
+ "FAMILY_10IOAXX",
66
+ "HOLDING_ADDRESS",
67
+ "HOLDING_AUTO_REPORT",
68
+ "HOLDING_BAUDRATE",
69
+ "HOLDING_FACTORY_RESET",
70
+ "HOLDING_INPUTS",
71
+ "HOLDING_OUTPUTS",
72
+ "HOLDING_PARITY",
73
+ "HOLDING_PRODUCT_ID",
74
+ "HOLDING_RELATION",
75
+ "HOLDING_RETURN_TIME",
76
+ "HOLDING_SETTINGS_COUNT",
77
+ "HOLDING_SETTINGS_START",
78
+ "MANUFACTURER",
79
+ "MAX_ADDRESS",
80
+ "MAX_AUTO_REPORT_SECONDS",
81
+ "MAX_RETURN_TIME_MS",
82
+ "MIN_ADDRESS",
83
+ "PROFILES",
84
+ "AnalogChannel",
85
+ "ChannelOutOfRangeError",
86
+ "CorrectionKind",
87
+ "DeviceProfile",
88
+ "EletechsupDevice",
89
+ "EletechsupError",
90
+ "Layout",
91
+ "MaskRegistersLayout",
92
+ "Parity",
93
+ "RelationMode",
94
+ "SettingsSnapshot",
95
+ "UnknownFamilyError",
96
+ "UnknownLayoutError",
97
+ "UnknownModelError",
98
+ "UnknownVariantError",
99
+ "ValueNotStoredError",
100
+ "ValueOutOfRangeError",
101
+ "__version__",
102
+ "build_registry",
103
+ "families",
104
+ "profile_for_model",
105
+ "profile_for_model_in_family",
106
+ "profile_for_product_id",
107
+ "profiles_for_family",
108
+ "require_profile",
109
+ ]