feat: initial release of s4k modbus relay controller v1.0.0-linux

This commit is contained in:
2026-04-10 14:00:26 +03:00
commit c3825ff105
5 changed files with 562 additions and 0 deletions
+223
View File
@@ -0,0 +1,223 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[codz]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py.cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
# Pipfile.lock
# UV
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# uv.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
# poetry.lock
# poetry.toml
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
# pdm.lock
# pdm.toml
.pdm-python
.pdm-build/
# pixi
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
# pixi.lock
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
# in the .venv directory. It is recommended not to include this directory in version control.
.pixi
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# Redis
*.rdb
*.aof
*.pid
# RabbitMQ
mnesia/
rabbitmq/
rabbitmq-data/
# ActiveMQ
activemq-data/
# SageMath parsed files
*.sage.py
# Environments
.env
.envrc
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
# .idea/
# Abstra
# Abstra is an AI-powered process automation framework.
# Ignore directories containing user credentials, local state, and settings.
# Learn more at https://abstra.io/docs
.abstra/
# Visual Studio Code
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
# and can be added to the global gitignore or merged into this file. However, if you prefer,
# you could uncomment the following to ignore the entire vscode folder
# .vscode/
# Ruff stuff:
.ruff_cache/
# PyPI configuration file
.pypirc
# Marimo
marimo/_static/
marimo/_lsp/
__marimo__/
# Streamlit
.streamlit/secrets.toml
# Manual additions
*.ini
# Project files, i.e. `.project`, `.actionScriptProperties` and `.flexProperties`
# should NOT be excluded as they contain compiler settings and other important
# information for Eclipse / Flash Builder.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Andrii Syrovatko
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+94
View File
@@ -0,0 +1,94 @@
# 🛰 S4K Modbus Relay Control
A lightweight, zero-dependency Python utility for controlling [Ethernet/PoE Modbus Relays](https://www.waveshare.com/wiki/Modbus_POE_ETH_Relay) (specifically tested with Waveshare modules).\
Designed for stability in production environments where reliability is key.
---
### 📋 Features
* **Direct Socket Communication:** No heavy libraries like `pymodbus` required.
* **Instance Protection:** Uses `fcntl` file locking to prevent race conditions during concurrent executions.
* **Health Checks:** Integrated `ICMP` ping check before command execution.
* **Configurable:** All parameters (IP, Port, Channels) are stored in an external `.ini` file.
* **Detailed Logging:** Full audit trail of all `ON/OFF/TOGGLE` actions.
---
### 💻 Requirements
| Requirement | Value |
| :--- | :--- |
| **OS** | Linux (Ubuntu, Debian, LMDE, etc.) |
| **Python** | 3.6+ |
| **Permissions** | Write access to log/lock paths |
---
### ⚙️ Configuration (`config.ini`)
| Section | Parameter | Description | Default |
| :--- | :--- | :--- | :--- |
| **`[modbus]`** | `host` | IP address of the relay | `192.168.X.X` |
| **`[modbus]`** | `port` | TCP port (Waveshare: `4196`) | `4196` |
| **`[modbus]`** | `unit` | Modbus Unit ID | `1` |
| **`[modbus]`** | `coil_base` | Channel base num (`0` or `1`) | `1` |
| **`[modbus]`** | `timeout` | Socket timeout (sec) (only view) | `1` |
| **`[modbus]`** | `max_channel`| Max channel index (e.g., `7`). `7` for `coil_base=1` too. | `7` |
| **`[paths]`** | `lock_file` | Path to `.lock` file | `/tmp/modbus.lock` |
| **`[paths]`** | `log_file` | Path to `.log` file | `/tmp/modbus.log` |
---
### ⚙️ Installation & Setup
1. Clone the repository:
```bash
git clone https://github.com/andsyrovatko/s4k-modbus-relay-controller.git
cd s4k-modbus-relay-controller
```
2. Configure the tool:
Copy the example config and edit it with your device details:
```bash
cp config.ini.example config.ini
nano config.ini
```
3. Set executable permissions:
```bash
chmod +x modbus_controller.py
```
---
### 🚀 Usage
0. Use via cli or call from another soft:
```bash
# Get script help/usage info
python3 modbus_controller.py
# Output: modbus_controller.py <status|on|off|toggle> <channel>
# Get channel status
python3 modbus_controller.py status 8
# Output: Channel 8 is OFF
# Turn a specific channel ON or OFF
python3 modbus_controller.py on 8
# Output: Channel 8 is turned ON
# Toggle channel state
python3 modbus_controller.py toggle 8
# Output: Channel 8 is turned ON
```
---
### ⚠️ Important Note
[**!IMPORTANT**]\
This version currently supports Linux only due to the use of fcntl for process locking. Windows support is planned for future releases.
---
### ⚠️ Disclaimer
> **Use at your own risk!** These scripts are designed for administrative tasks and may perform destructive actions (like killing processes or deleting config files). The author is not responsible for any data loss or system instability. Always test in a sandbox environment first.
---
### ⚖️ License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
+11
View File
@@ -0,0 +1,11 @@
[modbus]
host = 192.168.X.X # IP address of the Modbus device
port = 4196 # Port number for the Modbus device
unit = 1 # Unit ID for the Modbus channel
coil_base = 1 # Base address for coils (0 for 0-7 channel use, 1 for 1-8 channel use)
timeout = 1 # Timeout value in seconds
max_channel = 7 # Maximum number of channels of the Modbus device model (7 - 0-7, as 8 channels summary)
[paths]
lock_file = /tmp/modbus_controller.lock
log_file = /tmp/modbus_controller.log
+213
View File
@@ -0,0 +1,213 @@
#!/usr/bin/env python3
# =============================================================================
# Script Name : modbus_controller.py
# Description : Control Modbus coils via TCP (Modbus RTU over TCP).
# Usage : python3 modbus_controller.py <status|on|off|toggle> <channel>
# Author : syr4ok (Andrii Syrovatko)
# Version : 1.0.0-linux
# =============================================================================
import configparser
import os
import socket
import sys
import time
import subprocess
import logging
import fcntl
# Read configuration (variables will be used later in the code)
config = configparser.ConfigParser(inline_comment_prefixes=('#', ';'))
config_path = os.path.join(os.path.dirname(__file__), 'config.ini')
config.read(config_path)
# Reading variables (with type conversion)
HOST = config.get('modbus', 'host')
PORT = config.getint('modbus', 'port')
UNIT = config.getint('modbus', 'unit')
COIL_BASE = config.getint('modbus', 'coil_base')
TIMEOUT = config.getint('modbus', 'timeout')
MAX_CHANNEL = config.getint('modbus', 'max_channel')
LOCK_FILE = config.get('paths', 'lock_file')
LOG_FILE = config.get('paths', 'log_file')
log_dir = os.path.dirname(LOG_FILE)
if not os.path.exists(log_dir):
try:
os.makedirs(log_dir, exist_ok=True)
except OSError as e:
print(f"Error: Cannot create log directory {log_dir}: {e}")
# Use local log file as instead
LOG_FILE = "modbus_controller.log"
logging.basicConfig(
filename=LOG_FILE,
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
datefmt="%Y-%m-%d at %H:%M:%S"
)
lock_fp = open(LOCK_FILE, "w")
try:
fcntl.flock(lock_fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
print("Another instance is already running.")
sys.exit(1)
def is_host_reachable(host):
try:
result = subprocess.run(
["ping", "-c", "1", "-W", "1", host],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
return result.returncode == 0
except Exception:
return False
def modbus_crc(data):
"""CALC CRC16 Modbus"""
crc = 0xFFFF
for a in data:
crc ^= a
for _ in range(8):
if crc & 0x0001:
crc = (crc >> 1) ^ 0xA001
else:
crc >>= 1
return crc
def build_write_cmd(channel, state):
cmd = [0] * 8
cmd[0] = UNIT
cmd[1] = 0x05 # Write Single Coil
cmd[2] = 0x00
cmd[3] = channel
cmd[4] = 0xFF if state else 0x00
cmd[5] = 0x00
crc = modbus_crc(cmd[0:6])
cmd[6] = crc & 0xFF
cmd[7] = crc >> 8
return bytearray(cmd)
def build_read_cmd(channel):
cmd = [0] * 8
cmd[0] = UNIT
cmd[1] = 0x01 # Read Coils
cmd[2] = 0x00
cmd[3] = channel
cmd[4] = 0x00
cmd[5] = 0x01
crc = modbus_crc(cmd[0:6])
cmd[6] = crc & 0xFF
cmd[7] = crc >> 8
return bytearray(cmd)
def read_status(sock, channel):
sock.send(build_read_cmd(channel))
try:
resp = sock.recv(8)
if len(resp) >= 4:
return bool(resp[3] & 0x01)
except socket.timeout:
pass
return None
def write_channel(sock, channel, state):
sock.send(build_write_cmd(channel, state))
time.sleep(0.1)
def toggle_channel(sock, channel):
state = read_status(sock, channel)
if state is None:
print(f"Channel {channel + COIL_BASE} did not respond")
return
write_channel(sock, channel, not state)
def usage():
print(f"Usage: {sys.argv[0]} <status|on|off|toggle> <channel>")
sys.exit(1)
if len(sys.argv) != 3:
usage()
# Command and channel processing
command_input = sys.argv[1].lower()
channel_input = sys.argv[2]
# Converting ON/OFF into a command
if command_input in ['on', 'off', 'toggle', 'status']:
command = command_input
else:
# Attempt to accept "ON"/"OFF" as a command
if command_input.upper() == 'ON':
command = 'on'
elif command_input.upper() == 'OFF':
command = 'off'
else:
usage()
try:
channel = int(channel_input) - COIL_BASE
except ValueError:
print("Channel must be an integer")
sys.exit(1)
if not (0 <= channel <= MAX_CHANNEL):
print(f"Channel must be between {COIL_BASE} and {COIL_BASE + MAX_CHANNEL}")
sys.exit(1)
if not is_host_reachable(HOST):
error_msg = f"Host Modbus ({HOST}) is not reachable (ping failed)"
print(error_msg)
logging.error(error_msg)
sys.exit(1)
try:
with socket.socket() as s:
s.settimeout(TIMEOUT)
s.connect((HOST, PORT))
if command == "status":
state = read_status(s, channel)
if state is None:
print(f"Channel {channel + COIL_BASE} did not respond")
else:
print(f"Channel {channel + COIL_BASE} is {'ON' if state else 'OFF'}")
elif command == "on":
state_before = read_status(s, channel)
if state_before is None:
print(f"Channel {channel + COIL_BASE} did not respond")
elif state_before:
print(f"Channel {channel + COIL_BASE} is already ON, no action taken")
else:
write_channel(s, channel, True)
print(f"Channel {channel + COIL_BASE} is turned ON")
logging.info(f"ON command sent to channel {channel + COIL_BASE}")
elif command == "off":
state_before = read_status(s, channel)
if state_before is None:
print(f"Channel {channel + COIL_BASE} did not respond")
elif not state_before:
print(f"Channel {channel + COIL_BASE} is already OFF, no action taken")
else:
write_channel(s, channel, False)
print(f"Channel {channel + COIL_BASE} is turned OFF")
logging.info(f"OFF command sent to channel {channel + COIL_BASE}")
elif command == "toggle":
state_before = read_status(s, channel)
toggle_channel(s, channel)
if state_before is None:
print(f"Channel {channel + COIL_BASE} did not respond")
else:
print(f"Channel {channel + COIL_BASE} is turned {'OFF' if state_before else 'ON'}")
logging.info(f"TOGGLE {'-->OFF' if state_before else '-->ON'} command sent to channel {channel + COIL_BASE}")
else:
usage()
except (socket.timeout, ConnectionRefusedError, OSError) as e:
error_msg = f"Connection error to host Modbus ({HOST}:{PORT}) - {e}"
print(error_msg)
logging.error(error_msg)
sys.exit(1)
sys.exit(0)