Add Modbus support and update UI/backend installers

This commit is contained in:
Andrei Smaliak 2026-04-06 12:33:29 +04:00
parent 8e908bb752
commit 01f5b4da0d
10 changed files with 3039 additions and 8 deletions

1
.gitignore vendored
View File

@ -11,3 +11,4 @@ __pycache__/
*.zip *.zip
*:Zone.Identifier *:Zone.Identifier
client/

View File

@ -655,6 +655,8 @@ RuntimeDirectoryMode=0755
Environment=ITSCREEN_DISPLAY=:0 Environment=ITSCREEN_DISPLAY=:0
Environment=ITSCREEN_VT=vt7 Environment=ITSCREEN_VT=vt7
ExecStartPre=/usr/bin/nm-online -s -q --timeout=45 ExecStartPre=/usr/bin/nm-online -s -q --timeout=45
# Fix intermittent black screen caused by HDMI/DRM/X startup race on RK3568.
ExecStartPre=/bin/bash -ec 'for ((i=0; i<15; i++)); do if [[ -e /sys/class/drm/card0-HDMI-A-1 ]] && [[ "$(< /sys/class/drm/card0-HDMI-A-1/status)" == "connected" ]]; then /bin/sleep 2; exit 0; fi; /bin/sleep 1; done; echo "HDMI not ready after timeout" >&2; exit 1'
ExecStartPre=/usr/local/bin/itscreen-x11-cleanup ExecStartPre=/usr/local/bin/itscreen-x11-cleanup
ExecStart=/usr/local/bin/itscreen-x11-launch ExecStart=/usr/local/bin/itscreen-x11-launch
ExecStopPost=/usr/local/bin/itscreen-x11-cleanup ExecStopPost=/usr/local/bin/itscreen-x11-cleanup

View File

@ -15,6 +15,20 @@ from datetime import datetime
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse from urllib.parse import parse_qs, urlparse
from itscreen_registration import get_registration_status, register_device, reset_registration from itscreen_registration import get_registration_status, register_device, reset_registration
from modbus_backend import (
ApiError as ModbusApiError,
acquire_session as modbus_acquire_session,
get_discovery_job as modbus_get_discovery_job,
list_ports_payload as modbus_list_ports_payload,
profiles_payload as modbus_profiles_payload,
read_audit as modbus_read_audit,
read_device_config as modbus_read_device_config,
read_registers as modbus_read_registers,
release_session as modbus_release_session,
start_discovery as modbus_start_discovery,
write_device_config as modbus_write_device_config,
write_register as modbus_write_register,
)
APP_DIR = "/opt/iomatex-console" APP_DIR = "/opt/iomatex-console"
PUBLIC_DIR = os.path.join(APP_DIR, "public") PUBLIC_DIR = os.path.join(APP_DIR, "public")
@ -1886,13 +1900,20 @@ class Handler(BaseHTTPRequestHandler):
def log_message(self, fmt, *args): def log_message(self, fmt, *args):
return return
def _write_response_body(self, body):
try:
self.wfile.write(body)
except (BrokenPipeError, ConnectionResetError):
return False
return True
def send_json(self, payload, code=200): def send_json(self, payload, code=200):
body = json.dumps(payload, indent=2).encode("utf-8") body = json.dumps(payload, indent=2).encode("utf-8")
self.send_response(code) self.send_response(code)
self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body))) self.send_header("Content-Length", str(len(body)))
self.end_headers() self.end_headers()
self.wfile.write(body) self._write_response_body(body)
def send_html(self, html, code=200, extra_headers=None): def send_html(self, html, code=200, extra_headers=None):
body = html.encode("utf-8") body = html.encode("utf-8")
@ -1905,7 +1926,7 @@ class Handler(BaseHTTPRequestHandler):
for key, value in extra_headers.items(): for key, value in extra_headers.items():
self.send_header(key, value) self.send_header(key, value)
self.end_headers() self.end_headers()
self.wfile.write(body) self._write_response_body(body)
def send_redirect(self, location, code=302, extra_headers=None): def send_redirect(self, location, code=302, extra_headers=None):
self.send_response(code) self.send_response(code)
@ -1938,7 +1959,7 @@ class Handler(BaseHTTPRequestHandler):
self.send_header("Content-Type", content_type) self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(data))) self.send_header("Content-Length", str(len(data)))
self.end_headers() self.end_headers()
self.wfile.write(data) self._write_response_body(data)
def send_sse_headers(self): def send_sse_headers(self):
self.send_response(200) self.send_response(200)
@ -2082,6 +2103,40 @@ class Handler(BaseHTTPRequestHandler):
except Exception as exc: except Exception as exc:
self.send_json({"ok": False, "error": str(exc), "networks": []}, code=500) self.send_json({"ok": False, "error": str(exc), "networks": []}, code=500)
return return
if parsed.path == "/api/modbus/ports":
try:
self.send_json(modbus_list_ports_payload())
except ModbusApiError as exc:
self.send_json({"ok": False, "error": exc.message, "details": exc.details}, code=exc.code)
except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=500)
return
if parsed.path == "/api/modbus/profiles":
try:
self.send_json(modbus_profiles_payload())
except ModbusApiError as exc:
self.send_json({"ok": False, "error": exc.message, "details": exc.details}, code=exc.code)
except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=500)
return
if parsed.path == "/api/modbus/audit":
try:
limit = int((query.get("limit") or [120])[0])
self.send_json(modbus_read_audit(limit))
except ModbusApiError as exc:
self.send_json({"ok": False, "error": exc.message, "details": exc.details}, code=exc.code)
except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=500)
return
if parsed.path.startswith("/api/modbus/discover/"):
job_id = parsed.path.rsplit("/", 1)[-1]
try:
self.send_json(modbus_get_discovery_job(job_id))
except ModbusApiError as exc:
self.send_json({"ok": False, "error": exc.message, "details": exc.details}, code=exc.code)
except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=500)
return
if parsed.path == "/api/itscreen/status": if parsed.path == "/api/itscreen/status":
try: try:
self.send_json(build_itscreen_status_payload()) self.send_json(build_itscreen_status_payload())
@ -2254,6 +2309,141 @@ class Handler(BaseHTTPRequestHandler):
except Exception as exc: except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=500) self.send_json({"ok": False, "error": str(exc)}, code=500)
return return
if parsed.path == "/api/modbus/session/acquire":
payload = self.read_json_body()
if payload is None:
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
return
try:
self.send_json(modbus_acquire_session(
str(payload.get("port", "")),
bool(payload.get("stop_itscreen", False)),
source="console_ui",
))
except ModbusApiError as exc:
self.send_json({"ok": False, "error": exc.message, "details": exc.details}, code=exc.code)
except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=500)
return
if parsed.path == "/api/modbus/session/release":
payload = self.read_json_body()
if payload is None:
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
return
try:
self.send_json(modbus_release_session(
str(payload.get("port", "")),
bool(payload.get("restart_itscreen", False)),
source="console_ui",
))
except ModbusApiError as exc:
self.send_json({"ok": False, "error": exc.message, "details": exc.details}, code=exc.code)
except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=500)
return
if parsed.path == "/api/modbus/discover":
payload = self.read_json_body()
if payload is None:
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
return
try:
self.send_json(modbus_start_discovery(
port=str(payload.get("port", "")),
family=str(payload.get("family", "")),
slave_range=list(payload.get("slave_range") or [1, 10]),
baud=int(payload.get("baud", 9600)),
parity=str(payload.get("parity", "none")),
deep=bool(payload.get("deep", False)),
source="console_ui",
))
except ModbusApiError as exc:
self.send_json({"ok": False, "error": exc.message, "details": exc.details, "devices": [], "scan_log": []}, code=exc.code)
except Exception as exc:
self.send_json({"ok": False, "error": str(exc), "devices": [], "scan_log": []}, code=500)
return
if parsed.path == "/api/modbus/read-config":
payload = self.read_json_body()
if payload is None:
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
return
try:
self.send_json(modbus_read_device_config(
port=str(payload.get("port", "")),
family=str(payload.get("family", "")),
slave=int(payload.get("slave", 1)),
baud=int(payload.get("baud", 9600)),
parity=str(payload.get("parity", "none")),
source="console_ui",
))
except ModbusApiError as exc:
self.send_json({"ok": False, "error": exc.message, "details": exc.details}, code=exc.code)
except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=500)
return
if parsed.path == "/api/modbus/write-config":
payload = self.read_json_body()
if payload is None:
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
return
try:
self.send_json(modbus_write_device_config(
port=str(payload.get("port", "")),
family=str(payload.get("family", "")),
baudrate=int(payload.get("baudrate", 9600)),
current=payload.get("current") or {},
target=payload.get("target") or {},
strategy=str(payload.get("strategy", "both")),
source="console_ui",
))
except ModbusApiError as exc:
self.send_json({"ok": False, "error": exc.message, "details": exc.details}, code=exc.code)
except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=500)
return
if parsed.path == "/api/modbus/register/read":
payload = self.read_json_body()
if payload is None:
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
return
try:
self.send_json(modbus_read_registers(
port=str(payload.get("port", "")),
family=str(payload.get("family", "")),
slave=int(payload.get("slave", 1)),
baud=int(payload.get("baud", 9600)),
parity=str(payload.get("parity", "none")),
address=int(payload.get("address", 0)),
count=int(payload.get("count", 1)),
register_type=str(payload.get("register_type", "holding")),
decode_mode=str(payload.get("decode_mode", "uint16")),
source="console_ui",
))
except ModbusApiError as exc:
self.send_json({"ok": False, "error": exc.message, "details": exc.details}, code=exc.code)
except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=500)
return
if parsed.path == "/api/modbus/register/write":
payload = self.read_json_body()
if payload is None:
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
return
try:
self.send_json(modbus_write_register(
port=str(payload.get("port", "")),
family=str(payload.get("family", "")),
slave=int(payload.get("slave", 1)),
baud=int(payload.get("baud", 9600)),
parity=str(payload.get("parity", "none")),
address=int(payload.get("address", 0)),
value=int(payload.get("value", 0)),
source="console_ui",
))
except ModbusApiError as exc:
self.send_json({"ok": False, "error": exc.message, "details": exc.details}, code=exc.code)
except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=500)
return
if parsed.path == "/api/actions/audio-test": if parsed.path == "/api/actions/audio-test":
payload = self.read_json_body() payload = self.read_json_body()
if payload is None: if payload is None:

File diff suppressed because it is too large Load Diff

View File

@ -906,6 +906,169 @@ html[dir="rtl"] .itscreenLogsActions{
.logEmpty{ .logEmpty{
color:var(--log-empty); color:var(--log-empty);
} }
.checkboxRow{
display:flex;
align-items:flex-start;
gap:10px;
font-size:14px;
color:var(--muted);
}
.checkboxRow input{margin-top:3px}
.modbusGrid{
display:grid;
grid-template-columns:repeat(2,minmax(0,1fr));
gap:14px;
align-items:start;
}
.modbusDiscoveryGrid{
grid-template-columns:repeat(2,minmax(220px,1fr));
row-gap:16px;
}
.modbusTableWrap{
overflow:auto;
border:1px solid var(--line);
border-radius:14px;
}
.modbusTable{
width:100%;
border-collapse:collapse;
font-size:14px;
}
.modbusTable th,
.modbusTable td{
padding:10px 12px;
border-bottom:1px solid var(--line);
text-align:left;
vertical-align:top;
}
.modbusTable th{
font-size:12px;
text-transform:uppercase;
letter-spacing:.08em;
color:var(--muted);
background:rgba(255,255,255,.03);
}
.modbusTable tr.is-selected{
background:rgba(47,154,111,.1);
}
.compactActionRow{
gap:8px;
flex-wrap:wrap;
}
.compactBtn{
padding:8px 10px;
min-height:auto;
font-size:12px;
}
.statusBadge{
display:inline-flex;
align-items:center;
padding:4px 10px;
border-radius:999px;
font-size:12px;
font-weight:700;
text-transform:uppercase;
letter-spacing:.04em;
background:rgba(255,255,255,.06);
}
.statusBadge.is-ok{
background:rgba(14,122,83,.12);
color:var(--accent);
}
.modbusLogPanel{
display:grid;
gap:10px;
max-height:320px;
overflow:auto;
padding-right:4px;
}
.modbusLogEntry{
display:grid;
gap:4px;
padding:10px 12px;
border:1px solid var(--line);
border-radius:12px;
background:rgba(255,255,255,.03);
}
.modbusLogEntry.is-success{border-color:rgba(47,154,111,.4)}
.modbusLogEntry.is-warn{border-color:rgba(224,176,72,.4)}
.modbusLogEntry.is-error{border-color:rgba(196,78,82,.5)}
.modbusLogTime{
font-size:12px;
color:var(--muted);
}
.modbusLogMessage{
font-size:14px;
line-height:1.45;
}
.modbusScanActions{
align-items:center;
margin-top:16px;
}
.modbusScanLogBody{
min-height:180px;
max-height:280px;
overflow:auto;
padding:12px 14px;
border:1px solid var(--line);
border-radius:14px;
background:var(--log-bg);
color:var(--log-ink);
font-family:ui-monospace,SFMono-Regular,Menlo,monospace;
font-size:12px;
line-height:1.5;
}
.scanLogCard{
margin-top:16px;
}
.advancedSection{
display:grid;
gap:12px;
margin-bottom:18px;
}
.technicalDetails{
margin-top:12px;
}
.technicalDetails summary{
cursor:pointer;
color:var(--muted);
font-size:13px;
}
.technicalDetails .diagBlock{
margin-top:10px;
max-height:260px;
}
.modbusSummaryMeta{
margin-top:12px;
}
.writeConfigSection{
display:grid;
gap:12px;
margin-top:14px;
}
.sectionTitle{
font-size:13px;
font-weight:700;
color:var(--muted);
letter-spacing:.04em;
text-transform:uppercase;
}
.writeLogCard{
margin-top:14px;
}
.modbusWriteLogBody{
min-height:160px;
max-height:160px;
overflow-y:auto;
padding:12px 14px;
border:1px solid var(--line);
border-radius:14px;
background:var(--log-bg);
color:var(--log-ink);
font-family:ui-monospace,SFMono-Regular,Menlo,monospace;
font-size:12px;
line-height:1.5;
}
@keyframes pulse{ @keyframes pulse{
0%,100%{opacity:.35;transform:scale(.9)} 0%,100%{opacity:.35;transform:scale(.9)}
50%{opacity:1;transform:scale(1)} 50%{opacity:1;transform:scale(1)}
@ -930,6 +1093,8 @@ html[dir="rtl"] .itscreenLogsActions{
.itscreenCards{grid-template-columns:1fr} .itscreenCards{grid-template-columns:1fr}
.itscreenLogsToolbar{grid-template-columns:1fr} .itscreenLogsToolbar{grid-template-columns:1fr}
.itscreenLogsActions{justify-content:flex-start} .itscreenLogsActions{justify-content:flex-start}
.modbusGrid{grid-template-columns:1fr}
.modbusDiscoveryGrid{grid-template-columns:1fr}
} }
@media (max-width:680px){ @media (max-width:680px){
.menuToggleBtn{ .menuToggleBtn{
@ -956,4 +1121,8 @@ html[dir="rtl"] .itscreenLogsActions{
} }
.tunnelTableHead{display:none} .tunnelTableHead{display:none}
.tunnelCompactRow{padding:9px 0} .tunnelCompactRow{padding:9px 0}
.modbusTable th,
.modbusTable td{
min-width:120px;
}
} }

View File

@ -23,6 +23,7 @@
rebootMenuLabel: document.getElementById("rebootMenuLabel"), rebootMenuLabel: document.getElementById("rebootMenuLabel"),
tabHealth: document.getElementById("tabHealth"), tabHealth: document.getElementById("tabHealth"),
tabNetwork: document.getElementById("tabNetwork"), tabNetwork: document.getElementById("tabNetwork"),
tabModbus: document.getElementById("tabModbus"),
tabTscreen: document.getElementById("tabTscreen"), tabTscreen: document.getElementById("tabTscreen"),
tabGbox: document.getElementById("tabGbox"), tabGbox: document.getElementById("tabGbox"),
edgeId: document.getElementById("edgeId"), edgeId: document.getElementById("edgeId"),
@ -176,6 +177,57 @@
} }
}, },
scan: { ok: true, networks: [], error: "", warning: "", message: "", loading: false, scannedAt: "", expanded: false, lastTriggeredAt: 0 }, scan: { ok: true, networks: [], error: "", warning: "", message: "", loading: false, scannedAt: "", expanded: false, lastTriggeredAt: 0 },
modbus: {
loading: false,
ports: [],
profiles: [],
audit: [],
error: "",
loadedAt: 0,
request: null,
operationLog: [],
busyAction: "",
stopItscreen: true,
restartItscreen: true,
port: "/dev/ttyS3",
family: "ultrasonic_water_meter",
mode: "simple",
advancedOpen: false,
session: null,
discovery: {
slaveFrom: "1",
slaveTo: "10",
baud: "9600",
parity: "none",
devices: [],
lastMode: "quick",
jobId: "",
state: "idle",
message: "",
scanLog: [],
checked: 0,
total: 0,
currentSlave: null
},
selectedDevice: null,
currentConfig: null,
lastWriteResult: null,
writeLog: [],
writeForm: {
slave: "",
baud: "9600",
parity: "none",
strategy: "both"
},
registerForm: {
address: "0",
count: "1",
registerType: "holding",
decodeMode: "uint16",
value: "",
lastResult: null
}
},
networkForm: { networkForm: {
ssid: "", ssid: "",
password: "", password: "",
@ -388,6 +440,7 @@
if (nodes.rebootMenuLabel) nodes.rebootMenuLabel.textContent = t("Reboot"); if (nodes.rebootMenuLabel) nodes.rebootMenuLabel.textContent = t("Reboot");
if (nodes.tabHealth) nodes.tabHealth.textContent = t("Health"); if (nodes.tabHealth) nodes.tabHealth.textContent = t("Health");
if (nodes.tabNetwork) nodes.tabNetwork.textContent = t("Network"); if (nodes.tabNetwork) nodes.tabNetwork.textContent = t("Network");
if (nodes.tabModbus) nodes.tabModbus.textContent = t("Modbus");
if (nodes.tabTscreen) nodes.tabTscreen.textContent = t("It-Screen"); if (nodes.tabTscreen) nodes.tabTscreen.textContent = t("It-Screen");
if (nodes.tabGbox) nodes.tabGbox.textContent = t("G-Box Instructions and Manual"); if (nodes.tabGbox) nodes.tabGbox.textContent = t("G-Box Instructions and Manual");
const nav = document.querySelector(".tabs"); const nav = document.querySelector(".tabs");
@ -2211,6 +2264,481 @@
} }
} }
function modbusState() {
return state.modbus;
}
function modbusOperationLogEntries(payload) {
const entries = Array.isArray(payload && payload.operation_log) ? payload.operation_log : [];
return entries.map((item) => ({
timestamp: new Date().toISOString(),
level: textValue(item.level, "info"),
message: textValue(item.message, "")
})).filter((item) => item.message);
}
function appendModbusLog(message, level = "info") {
if (!message) return;
const log = modbusState();
log.operationLog = [{ timestamp: new Date().toISOString(), level, message }].concat(log.operationLog || []).slice(0, 160);
}
function ingestModbusPayload(payload) {
const log = modbusState();
const entries = modbusOperationLogEntries(payload);
if (entries.length) {
log.operationLog = entries.concat(log.operationLog || []).slice(0, 160);
}
}
function parseIntCsv(value, fallback) {
const items = String(value || "").split(",").map((item) => Number(String(item).trim())).filter((item) => Number.isFinite(item) && item > 0);
return items.length ? items : fallback;
}
function parseTextCsv(value, fallback) {
const items = String(value || "").split(",").map((item) => String(item).trim().toLowerCase()).filter(Boolean);
return items.length ? items : fallback;
}
function modbusSelectedProfile() {
return (modbusState().profiles || []).find((item) => item.family === modbusState().family) || null;
}
function modbusSelectedPortStatus() {
return (modbusState().ports || []).find((item) => item.port === modbusState().port) || null;
}
function modbusCanWrite() {
const log = modbusState();
const currentConfig = log.currentConfig && log.currentConfig.current_config;
const supportsIdWrite = !!(currentConfig && currentConfig.supports_id_write);
const supportsSerialWrite = !!(currentConfig && currentConfig.supports_serial_write);
return !!(log.currentConfig && log.selectedDevice && (supportsIdWrite || supportsSerialWrite));
}
function modbusBusy(action) {
return modbusState().busyAction === action;
}
function modbusCurrentConnection() {
const log = modbusState();
if (log.currentConfig && log.currentConfig.current) return log.currentConfig.current;
if (log.selectedDevice) {
return {
slave: log.selectedDevice.slave,
baud: log.selectedDevice.baud,
parity: log.selectedDevice.parity
};
}
const profile = modbusSelectedProfile();
return {
slave: 1,
baud: Number(profile && profile.transport && profile.transport.default_baud) || 9600,
parity: textValue(profile && profile.transport && profile.transport.default_parity, "none")
};
}
function syncModbusWriteFormFromConfig() {
const log = modbusState();
const current = modbusCurrentConnection();
if (!log.writeForm.slave) log.writeForm.slave = String(current.slave || "");
if (!log.writeForm.baud) log.writeForm.baud = String(current.baud || "9600");
if (!log.writeForm.parity) log.writeForm.parity = textValue(current.parity, "none");
}
function modbusWriteCurrentConfigView() {
const log = modbusState();
const current = modbusCurrentConnection();
const currentConfig = log.currentConfig || {};
const currentMeta = currentConfig.current_config || {};
return {
slave: textValue(currentMeta.slave_id, textValue(current.slave, "-")),
baud: textValue(currentMeta.baud, textValue(current.baud, t("Unknown"))),
parity: textValue(currentMeta.parity, textValue(current.parity, t("Unknown"))),
status: textValue(log.lastWriteResult && log.lastWriteResult.status, textValue(currentConfig.status, "-"))
};
}
function modbusScanRunning() {
return modbusBusy("scan_quick") || modbusBusy("scan_deep");
}
function modbusDiscoveryLogLines() {
const entries = Array.isArray(modbusState().discovery.scanLog) ? modbusState().discovery.scanLog : [];
return entries.map((entry) => `[${formatUtc(entry.timestamp)}] ${entry.message}`);
}
function appendModbusWriteLog(message, level = "info") {
if (!message) return;
const log = modbusState();
log.writeLog = (log.writeLog || []).concat([{ timestamp: new Date().toISOString(), level, message }]).slice(-160);
}
function ingestModbusWritePayload(payload) {
const entries = Array.isArray(payload && payload.operation_log) ? payload.operation_log : [];
if (!entries.length) return;
const log = modbusState();
const mapped = entries.map((item) => ({
timestamp: new Date().toISOString(),
level: textValue(item.level, "info"),
message: textValue(item.message, "")
})).filter((item) => item.message);
log.writeLog = (log.writeLog || []).concat(mapped).slice(-160);
}
function scrollModbusWriteLogToBottom() {
window.requestAnimationFrame(() => {
const node = document.getElementById("modbusWriteLogBody");
if (node) node.scrollTop = node.scrollHeight;
});
}
async function modbusEnsureSession() {
const log = modbusState();
const portInfo = modbusSelectedPortStatus() || {};
if (log.session || portInfo.locked) {
return true;
}
const payload = await fetchJson("/api/modbus/session/acquire", {
method: "POST",
cache: "no-store",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ port: log.port, stop_itscreen: !!log.stopItscreen })
});
log.session = payload.lock || null;
ingestModbusPayload(payload);
appendModbusLog(payload.message || t("Port acquired"), "success");
await loadModbus({ force: true, maxAgeMs: 0 });
return true;
}
function renderModbusLogPanel() {
const entries = modbusState().operationLog || [];
return `
<article class="panel card wideCard">
<div class="cardTop"><div><h2>${esc(t("Operation Log / Output"))}</h2></div></div>
<div class="modbusLogPanel">
${entries.length ? entries.map((entry) => `
<div class="modbusLogEntry is-${esc(entry.level)}">
<span class="modbusLogTime">${esc(formatUtc(entry.timestamp))}</span>
<span class="modbusLogMessage">${esc(entry.message)}</span>
</div>
`).join("") : `<div class="emptyInline">${esc(t("No Modbus operations yet."))}</div>`}
</div>
</article>
`;
}
function renderModbusFoundDevices() {
const devices = modbusState().discovery.devices || [];
if (!devices.length) {
return `<div class="emptyInline">${esc(t("No devices discovered yet."))}</div>`;
}
return `
<div class="modbusTableWrap">
<table class="modbusTable">
<thead>
<tr>
<th>${esc(t("Port"))}</th>
<th>${esc(t("Family"))}</th>
<th>${esc(t("Slave ID"))}</th>
<th>${esc(t("Baud"))}</th>
<th>${esc(t("Parity"))}</th>
<th>${esc(t("Test register"))}</th>
<th>${esc(t("Status"))}</th>
<th>${esc(t("Action"))}</th>
</tr>
</thead>
<tbody>
${devices.map((item, index) => `
<tr class="${modbusState().selectedDevice && modbusState().selectedDevice.port === item.port && modbusState().selectedDevice.slave === item.slave && modbusState().selectedDevice.baud === item.baud && modbusState().selectedDevice.parity === item.parity ? "is-selected" : ""}">
<td>${esc(item.port)}</td>
<td>${esc(item.family_display_name || item.family)}</td>
<td>${esc(String(item.slave))}</td>
<td>${esc(String(item.baud))}</td>
<td>${esc(item.parity)}</td>
<td>${esc(String(item.test_register && item.test_register.address))}</td>
<td><span class="statusBadge is-${esc(item.status || "ok")}">${esc(item.status || "ok")}</span></td>
<td>
<div class="actionRow compactActionRow">
<button class="actionBtn compactBtn" type="button" onclick="window.__modbusSelectDevice(${index})">${esc(t("Select"))}</button>
<button class="actionBtn secondary compactBtn" type="button" onclick="window.__modbusReadConfigFromDiscovery(${index})">${esc(t("Read config"))}</button>
</div>
</td>
</tr>
`).join("")}
</tbody>
</table>
</div>
`;
}
function renderModbusCurrentConfig() {
const currentConfig = modbusState().currentConfig;
if (!currentConfig) {
return `<div class="emptyInline">${esc(t("Select a discovered device and read its config."))}</div>`;
}
const rows = [
{ label: t("Current slave id"), value: textValue(currentConfig.current_config && currentConfig.current_config.slave_id, "-") },
{ label: t("Current baud"), value: textValue(currentConfig.current_config && currentConfig.current_config.baud, t("Unknown")) },
{ label: t("Current parity"), value: textValue(currentConfig.current_config && currentConfig.current_config.parity, t("Unknown")) },
{ label: t("Config register values"), value: JSON.stringify(currentConfig.raw_values || {}) },
{ label: t("Last successful read"), value: textValue(currentConfig.last_successful_read, "-") },
{ label: t("Last communication timestamp"), value: textValue(currentConfig.last_communication_timestamp, "-") }
];
return `<div class="meta compactMeta">${renderKeyValueRows(rows)}</div>`;
}
function modbusWriteStatusMeta() {
const result = modbusState().lastWriteResult;
if (!result) return "";
const status = textValue(result.status, "");
const isSuccess = result.ok === true && status === "verified_target";
const level = isSuccess ? "success" : (status === "found_elsewhere" || status === "write_unconfirmed" ? "warn" : "error");
const message = textValue(result.message || result.recommended_next_step, status || t("Unknown"));
const summaryRows = [];
const finalConfig = result.final_detected_config || {};
const debug = result.debug || {};
const precheck = debug.precheck || {};
const requestedCurrent = result.current_requested || {};
const requestedTarget = result.target_requested || {};
const fromSlave = textValue(requestedCurrent.slave, textValue(precheck.current && precheck.current.slave, "-"));
const toSlave = textValue(finalConfig.slave, textValue(requestedTarget.slave, "-"));
if (fromSlave || toSlave) summaryRows.push({ label: t("Slave ID"), value: `${fromSlave} → ${toSlave}` });
summaryRows.push({ label: t("Baud"), value: textValue(finalConfig.baud, textValue(requestedTarget.baud, textValue(precheck.current && precheck.current.baud, "-"))) });
summaryRows.push({ label: t("Parity"), value: textValue(finalConfig.parity, textValue(requestedTarget.parity, textValue(precheck.current && precheck.current.parity, "-"))) });
summaryRows.push({ label: t("Verification status"), value: textValue(result.status, "-") });
const technicalJson = JSON.stringify(result.debug || {}, null, 2);
return `
<div class="banner ${esc(level)}">${esc(message)}</div>
<div class="meta compactMeta modbusSummaryMeta">${renderKeyValueRows(summaryRows)}</div>
<details class="technicalDetails">
<summary>${esc(t("Technical details"))}</summary>
<pre class="diagBlock">${esc(technicalJson)}</pre>
</details>
`;
}
function renderModbusWriteProcessLog() {
const entries = modbusState().writeLog || [];
return `
<article class="writeLogCard">
<div class="cardTop"><div><h3>${esc(t("Technical/process log"))}</h3></div></div>
<div class="modbusWriteLogBody" id="modbusWriteLogBody">
${entries.length ? entries.map((entry) => `<div class="logLine is-${esc(entry.level)}">[${esc(formatUtc(entry.timestamp))}] ${esc(entry.message)}</div>`).join("") : `<div class="logEmpty">${esc(t("No write log yet"))}</div>`}
</div>
</article>
`;
}
function renderModbusTab() {
const log = modbusState();
const profile = modbusSelectedProfile();
const profileTransport = (profile && profile.transport) || {};
const supportsSerialWrite = !!(profile && profile.supports_serial_write) || !!(log.currentConfig && log.currentConfig.current_config && log.currentConfig.current_config.supports_serial_write);
const supportsIdWrite = !!(profile && profile.supports_id_write) || !!(log.currentConfig && log.currentConfig.current_config && log.currentConfig.current_config.supports_id_write);
const portInfo = modbusSelectedPortStatus() || {};
const zeroBased = !!profileTransport.zero_based;
const scanRunning = modbusScanRunning();
const scanStatus = textValue(log.discovery.message, scanRunning ? t("Scanning in progress. It may take some minutes.") : "");
const scanLogLines = modbusDiscoveryLogLines();
const writeCurrentConfig = modbusWriteCurrentConfigView();
syncModbusWriteFormFromConfig();
return `
<section class="tabPanel">
<div class="cards">
<article class="panel card">
<div class="cardTop"><div><h2>${esc(t("Device Family"))}</h2></div></div>
${log.error ? `<div class="banner error">${esc(log.error)}</div>` : ""}
<label class="field">
<span>${esc(t("Family"))}</span>
<select onchange="window.__modbusSetFamily(this.value)">
${(log.profiles || []).map((item) => `<option value="${esc(item.family)}" ${log.family === item.family ? "selected" : ""}>${esc(item.display_name || item.title || item.family)}</option>`).join("")}
</select>
</label>
<div class="formHint">${esc(t("Families are loaded from backend profile JSON files."))}</div>
<div class="meta compactMeta">
<div class="key">${esc(t("Default port"))}</div><div>${esc(textValue(profileTransport.default_port, "-"))}</div>
<div class="key">${esc(t("Default profile"))}</div><div>${esc(`${textValue(profileTransport.default_baud, "9600")}-${textValue(profileTransport.default_databits, "8")}${textValue(profileTransport.default_parity, "N")[0].toUpperCase()}${textValue(profileTransport.default_stopbits, "1")}`)}</div>
<div class="key">${esc(t("Addressing"))}</div><div>${esc(zeroBased ? t("Zero-based") : t("One-based"))}</div>
<div class="key">${esc(t("Serial profile write"))}</div><div>${esc(supportsSerialWrite ? t("Configured") : t("Not configured"))}</div>
</div>
</article>
<article class="panel card wideCard">
<div class="cardTop"><div><h2>${esc(t("Discovery"))}</h2></div></div>
<div class="modbusGrid modbusDiscoveryGrid">
<label class="field">
<span>${esc(t("UART port"))}</span>
<select onchange="window.__modbusSetPort(this.value)">
${(log.ports || []).map((item) => `<option value="${esc(item.port)}" ${log.port === item.port ? "selected" : ""}>${esc(item.port)}</option>`).join("")}
</select>
</label>
<label class="field">
<span>${esc(t("Slave from"))}</span>
<input type="number" min="1" max="247" value="${esc(log.discovery.slaveFrom)}" oninput="window.__modbusSetDiscovery('slaveFrom', this.value)">
</label>
<label class="field">
<span>${esc(t("Slave to"))}</span>
<input type="number" min="1" max="247" value="${esc(log.discovery.slaveTo)}" oninput="window.__modbusSetDiscovery('slaveTo', this.value)">
</label>
<label class="field">
<span>${esc(t("Baud rate"))}</span>
<select onchange="window.__modbusSetDiscovery('baud', this.value)">
${[1200,2400,4800,9600,19200,38400,57600,115200].map((item) => `<option value="${item}" ${String(log.discovery.baud) === String(item) ? "selected" : ""}>${esc(String(item))}</option>`).join("")}
</select>
</label>
<label class="field">
<span>${esc(t("Parity"))}</span>
<select onchange="window.__modbusSetDiscovery('parity', this.value)">
${["none","even","odd"].map((item) => `<option value="${item}" ${log.discovery.parity === item ? "selected" : ""}>${esc(item)}</option>`).join("")}
</select>
</label>
</div>
<div class="actionRow modbusScanActions">
<button class="actionBtn" type="button" ${scanRunning ? "disabled" : ""} onclick="window.__modbusScan('quick')">${esc(modbusBusy("scan_quick") ? t("Scanning...") : t("Quick scan"))}</button>
<button class="actionBtn secondary" type="button" ${scanRunning ? "disabled" : ""} onclick="window.__modbusScan('deep')">${esc(modbusBusy("scan_deep") ? t("Scanning...") : t("Deep scan"))}</button>
${scanRunning ? `<div class="loadingInline"><span class="loadingDot" aria-hidden="true"></span><span>${esc(t("Scanning in progress. It may take some minutes."))}${log.discovery.currentSlave ? ` ${esc(t("Current slave"))}: ${esc(String(log.discovery.currentSlave))}` : ""}${log.discovery.total ? ` (${esc(String(log.discovery.checked || 0))}/${esc(String(log.discovery.total))})` : ""}</span></div>` : ""}
</div>
${scanStatus && !scanRunning ? `<div class="formHint">${esc(scanStatus)}</div>` : ""}
<div class="formHint">${esc(zeroBased ? t("Use zero-based addressing for this device family.") : t("This device family uses one-based addressing."))}</div>
<article class="scanLogCard">
<div class="cardTop"><div><h2>${esc(t("Scan log"))}</h2></div></div>
<div class="modbusScanLogBody">${scanLogLines.length ? scanLogLines.map((line) => `<div class="logLine">${esc(line)}</div>`).join("") : `<div class="logEmpty">${esc(t("No scan activity yet."))}</div>`}</div>
</article>
</article>
<article class="panel card wideCard">
<div class="cardTop"><div><h2>${esc(t("Found Devices Table"))}</h2></div></div>
${renderModbusFoundDevices()}
</article>
<article class="panel card">
<div class="cardTop"><div><h2>${esc(t("Current Config"))}</h2></div></div>
${renderModbusCurrentConfig()}
</article>
<article class="panel card">
<div class="cardTop"><div><h2>${esc(t("Configuration Write"))}</h2></div></div>
${modbusWriteStatusMeta()}
${!supportsSerialWrite ? `<div class="formHint">${esc(t("Baud rate and parity write are not configured for this family yet. Slave ID write is available."))}</div>` : ""}
<div class="writeConfigSection">
<div class="sectionTitle">${esc(t("Current config"))}</div>
<div class="meta compactMeta modbusSummaryMeta">
${renderKeyValueRows([
{ label: t("Slave ID"), value: writeCurrentConfig.slave },
{ label: t("Baud"), value: writeCurrentConfig.baud },
{ label: t("Parity"), value: writeCurrentConfig.parity },
{ label: t("Verification status"), value: writeCurrentConfig.status }
])}
</div>
</div>
<div class="writeConfigSection">
<div class="sectionTitle">${esc(t("New values to write"))}</div>
<label class="field">
<span>${esc(t("New Slave ID"))}</span>
<input type="number" min="1" max="247" value="${esc(log.writeForm.slave)}" ${supportsIdWrite ? "" : "disabled"} oninput="window.__modbusSetWriteField('slave', this.value)">
</label>
<label class="field">
<span>${esc(t("New Baud Rate"))}</span>
<select onchange="window.__modbusSetWriteField('baud', this.value)">
${[1200,2400,4800,9600,19200,38400,57600,115200].map((item) => `<option value="${item}" ${String(log.writeForm.baud || "9600") === String(item) ? "selected" : ""}>${esc(String(item))}</option>`).join("")}
</select>
</label>
<label class="field">
<span>${esc(t("New Parity"))}</span>
<select ${supportsSerialWrite ? "" : "disabled"} onchange="window.__modbusSetWriteField('parity', this.value)">
${["none", "even", "odd"].map((item) => `<option value="${item}" ${log.writeForm.parity === item ? "selected" : ""}>${esc(item)}</option>`).join("")}
</select>
</label>
<label class="field">
<span>${esc(t("Apply strategy"))}</span>
<select onchange="window.__modbusSetWriteField('strategy', this.value)">
${(!supportsIdWrite && !supportsSerialWrite) ? `<option value="read_only" selected>${esc(t("Read only"))}</option>` : ""}
${supportsIdWrite ? `<option value="id_only" ${log.writeForm.strategy === "id_only" ? "selected" : ""}>${esc(t("ID only"))}</option>` : ""}
${supportsSerialWrite ? `<option value="serial_only" ${log.writeForm.strategy === "serial_only" ? "selected" : ""}>${esc(t("serial only"))}</option>` : ""}
${(supportsIdWrite && supportsSerialWrite) ? `<option value="both" ${log.writeForm.strategy === "both" ? "selected" : ""}>${esc(t("both"))}</option>` : ""}
</select>
</label>
</div>
<div class="formHint">${esc(t("Write is disabled until a device has been selected and its current config has been read."))}</div>
${renderModbusWriteProcessLog()}
<div class="actionRow">
<button class="actionBtn" type="button" ${modbusCanWrite() && !modbusBusy("write_config") ? "" : "disabled"} onclick="window.__modbusApplyConfig()">${esc(modbusBusy("write_config") ? t("Applying...") : t("Apply changes"))}</button>
</div>
</article>
<article class="panel card wideCard">
<div class="cardTop">
<div><h2>${esc(t("Advanced"))}</h2></div>
<div class="actionRow">
<button class="actionBtn secondary" type="button" onclick="window.__modbusToggleAdvanced()">${esc(log.advancedOpen ? t("Collapse") : t("Expand"))}</button>
</div>
</div>
${log.advancedOpen ? `
<div class="advancedSection">
<div class="cardTop"><div><h3>${esc(t("Session / Port Control"))}</h3></div></div>
${portInfo.itscreen_running ? `<div class="banner warn">${esc(t("it-screen service is running and may conflict with Modbus master access."))}</div>` : ""}
<div class="meta compactMeta">
<div class="key">${esc(t("Port status"))}</div><div>${esc(textValue(portInfo.status, "-"))}</div>
<div class="key">${esc(t("Busy process"))}</div><div>${esc((portInfo.busy_process || []).join(", ") || t("None"))}</div>
<div class="key">${esc(t("Lock owner"))}</div><div>${esc(textValue(portInfo.lock_owner, t("None")))}</div>
</div>
<label class="checkboxRow">
<input type="checkbox" ${log.stopItscreen ? "checked" : ""} onchange="window.__modbusSetToggle('stopItscreen', this.checked)">
<span>${esc(t("Stop it-screen while working with Modbus"))}</span>
</label>
<label class="checkboxRow">
<input type="checkbox" ${log.restartItscreen ? "checked" : ""} onchange="window.__modbusSetToggle('restartItscreen', this.checked)">
<span>${esc(t("Restart it-screen on release"))}</span>
</label>
<div class="actionRow">
<button class="actionBtn" type="button" ${modbusBusy("acquire") ? "disabled" : ""} onclick="window.__modbusAcquire()">${esc(modbusBusy("acquire") ? t("Acquiring...") : t("Acquire port"))}</button>
<button class="actionBtn secondary" type="button" ${modbusBusy("release") ? "disabled" : ""} onclick="window.__modbusRelease()">${esc(modbusBusy("release") ? t("Releasing...") : t("Release port"))}</button>
</div>
</div>
<div class="modbusGrid">
<label class="field">
<span>${esc(t("Register address"))}</span>
<input type="number" min="0" value="${esc(log.registerForm.address)}" oninput="window.__modbusSetRegisterField('address', this.value)">
</label>
<label class="field">
<span>${esc(t("Register type"))}</span>
<select onchange="window.__modbusSetRegisterField('registerType', this.value)">
${["holding", "input"].map((item) => `<option value="${item}" ${log.registerForm.registerType === item ? "selected" : ""}>${esc(item)}</option>`).join("")}
</select>
</label>
<label class="field">
<span>${esc(t("Count"))}</span>
<input type="number" min="1" max="20" value="${esc(log.registerForm.count)}" oninput="window.__modbusSetRegisterField('count', this.value)">
</label>
<label class="field">
<span>${esc(t("Decode mode"))}</span>
<select onchange="window.__modbusSetRegisterField('decodeMode', this.value)">
${["uint16", "int16", "hex"].map((item) => `<option value="${item}" ${log.registerForm.decodeMode === item ? "selected" : ""}>${esc(item)}</option>`).join("")}
</select>
</label>
<label class="field">
<span>${esc(t("Write value"))}</span>
<input type="number" value="${esc(log.registerForm.value)}" oninput="window.__modbusSetRegisterField('value', this.value)">
</label>
</div>
<div class="actionRow">
<button class="actionBtn secondary" type="button" ${!log.selectedDevice || modbusBusy("register_read") ? "disabled" : ""} onclick="window.__modbusReadRegister()">${esc(modbusBusy("register_read") ? t("Reading...") : t("Read"))}</button>
<button class="actionBtn secondary" type="button" ${!log.selectedDevice || modbusBusy("register_write") ? "disabled" : ""} onclick="window.__modbusWriteRegister()">${esc(modbusBusy("register_write") ? t("Writing...") : t("Write"))}</button>
</div>
${log.registerForm.lastResult ? `<pre class="diagBlock">${esc(JSON.stringify(log.registerForm.lastResult, null, 2))}</pre>` : `<div class="formHint">${esc(t("Register explorer is intended for engineering/debug mode."))}</div>`}
` : `<div class="formHint">${esc(t("Simple mode covers acquire, scan, read config, apply changes, rediscovery, and release."))}</div>`}
</article>
${renderModbusLogPanel()}
</div>
</section>
`;
}
function renderActiveTab() { function renderActiveTab() {
if (state.activeTab === "tscreen") { if (state.activeTab === "tscreen") {
captureItscreenLogViewport(); captureItscreenLogViewport();
@ -2224,6 +2752,10 @@
updateApFormUi(); updateApFormUi();
return; return;
} }
if (state.activeTab === "modbus") {
nodes.content.innerHTML = renderModbusTab();
return;
}
if (state.activeTab === "tscreen") { if (state.activeTab === "tscreen") {
nodes.content.innerHTML = renderTscreenTab(); nodes.content.innerHTML = renderTscreenTab();
updateItscreenLogsUi(); updateItscreenLogsUi();
@ -2280,6 +2812,58 @@
syncNetworkFormFromBackend(); syncNetworkFormFromBackend();
} }
async function loadModbus(options = {}) {
const log = modbusState();
const force = !!options.force;
const maxAgeMs = Number.isFinite(options.maxAgeMs) ? options.maxAgeMs : 8000;
if (!force && log.request) return log.request;
if (!force && log.loadedAt && Date.now() - log.loadedAt < maxAgeMs) return log;
log.loading = true;
log.request = (async () => {
try {
const [portsPayload, profilesPayload, auditPayload] = await Promise.all([
fetchJson("/api/modbus/ports", { cache: "no-store" }),
fetchJson("/api/modbus/profiles", { cache: "no-store" }),
fetchJson("/api/modbus/audit?limit=80", { cache: "no-store" })
]);
log.ports = Array.isArray(portsPayload.ports) ? portsPayload.ports : [];
log.profiles = Array.isArray(profilesPayload.profiles) ? profilesPayload.profiles : [];
log.audit = Array.isArray(auditPayload.entries) ? auditPayload.entries : [];
if (!log.port && log.ports.length) log.port = log.ports[0].port;
if (!log.family && log.profiles.length) log.family = log.profiles[0].family;
if (log.family && !log.profiles.some((item) => item.family === log.family) && log.profiles.length) {
log.family = log.profiles[0].family;
}
const selectedProfile = modbusSelectedProfile();
if (selectedProfile && selectedProfile.transport) {
if (!log.port && selectedProfile.transport.default_port) log.port = selectedProfile.transport.default_port;
log.discovery.baud = String(selectedProfile.transport.default_baud || 9600);
log.discovery.parity = textValue(selectedProfile.transport.default_parity, "none");
if (!["id_only", "serial_only", "both", "read_only"].includes(log.writeForm.strategy)) {
log.writeForm.strategy = selectedProfile.supports_id_write ? (selectedProfile.supports_serial_write ? "both" : "id_only") : (selectedProfile.supports_serial_write ? "serial_only" : "read_only");
}
}
if (!log.operationLog.length && log.audit.length) {
log.operationLog = log.audit.slice().reverse().map((item) => ({
timestamp: item.timestamp || new Date().toISOString(),
level: item.success === false ? "error" : "info",
message: item.message || `${item.action || "modbus"} ${item.port || ""}`.trim()
})).slice(0, 80);
}
log.error = "";
log.loadedAt = Date.now();
return log;
} catch (error) {
log.error = error.message || t("Failed to load Modbus data");
throw error;
} finally {
log.loading = false;
log.request = null;
}
})();
return log.request;
}
function syncItscreenFormFromBackend() { function syncItscreenFormFromBackend() {
const payload = itscreenRegistration(); const payload = itscreenRegistration();
const host = textValue(payload.server, textValue(payload.host, "")); const host = textValue(payload.server, textValue(payload.host, ""));
@ -2451,6 +3035,8 @@
await loadStatus(); await loadStatus();
if (state.activeTab === "network") { if (state.activeTab === "network") {
await loadNetwork(); await loadNetwork();
} else if (state.activeTab === "modbus") {
await loadModbus();
} else if (state.activeTab === "tscreen") { } else if (state.activeTab === "tscreen") {
await loadItscreen(); await loadItscreen();
} else if (state.activeTab === "health") { } else if (state.activeTab === "health") {
@ -2943,6 +3529,370 @@
updateItscreenLogsUi(); updateItscreenLogsUi();
}; };
window.__modbusSetPort = function (value) {
modbusState().port = value;
if (state.activeTab === "modbus") renderActiveTab();
};
window.__modbusSetFamily = function (value) {
const log = modbusState();
log.family = value;
log.currentConfig = null;
log.selectedDevice = null;
log.lastWriteResult = null;
const profile = modbusSelectedProfile();
if (profile && profile.transport) {
log.discovery.baud = String(profile.transport.default_baud || 9600);
log.discovery.parity = textValue(profile.transport.default_parity, "none");
log.writeForm.baud = String(profile.transport.default_baud || 9600);
log.writeForm.parity = textValue(profile.transport.default_parity, "none");
log.writeForm.strategy = profile.supports_id_write ? (profile.supports_serial_write ? "both" : "id_only") : (profile.supports_serial_write ? "serial_only" : "read_only");
}
if (state.activeTab === "modbus") renderActiveTab();
};
window.__modbusSetToggle = function (field, checked) {
modbusState()[field] = !!checked;
};
window.__modbusSetDiscovery = function (field, value) {
modbusState().discovery[field] = value;
};
window.__modbusSetWriteField = function (field, value) {
modbusState().writeForm[field] = value;
};
window.__modbusSetRegisterField = function (field, value) {
modbusState().registerForm[field] = value;
};
window.__modbusToggleAdvanced = function () {
modbusState().advancedOpen = !modbusState().advancedOpen;
if (state.activeTab === "modbus") renderActiveTab();
};
window.__modbusSelectDevice = function (index) {
const log = modbusState();
const item = (log.discovery.devices || [])[index];
if (!item) return;
log.selectedDevice = item;
log.writeForm.slave = String(item.slave);
log.writeForm.baud = String(item.baud);
log.writeForm.parity = item.parity;
appendModbusLog(t("Device selected for configuration work"), "info");
if (state.activeTab === "modbus") renderActiveTab();
};
window.__modbusAcquire = async function () {
const log = modbusState();
log.busyAction = "acquire";
log.error = "";
if (state.activeTab === "modbus") renderActiveTab();
try {
const payload = await fetchJson("/api/modbus/session/acquire", {
method: "POST",
cache: "no-store",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ port: log.port, stop_itscreen: !!log.stopItscreen })
});
log.session = payload.lock || null;
ingestModbusPayload(payload);
appendModbusLog(payload.message || t("Port acquired"), "success");
await loadModbus({ force: true, maxAgeMs: 0 });
showToast("success", payload.message || t("Port acquired"));
} catch (error) {
log.error = error.message || t("Failed to acquire port");
appendModbusLog(log.error, "error");
showToast("error", log.error);
} finally {
log.busyAction = "";
if (state.activeTab === "modbus") renderActiveTab();
}
};
window.__modbusRelease = async function () {
const log = modbusState();
log.busyAction = "release";
log.error = "";
if (state.activeTab === "modbus") renderActiveTab();
try {
const payload = await fetchJson("/api/modbus/session/release", {
method: "POST",
cache: "no-store",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ port: log.port, restart_itscreen: !!log.restartItscreen })
});
log.session = null;
ingestModbusPayload(payload);
appendModbusLog(payload.message || t("Port released"), "success");
await loadModbus({ force: true, maxAgeMs: 0 });
showToast("success", payload.message || t("Port released"));
} catch (error) {
log.error = error.message || t("Failed to release port");
appendModbusLog(log.error, "error");
showToast("error", log.error);
} finally {
log.busyAction = "";
if (state.activeTab === "modbus") renderActiveTab();
}
};
window.__modbusScan = async function (mode) {
const log = modbusState();
const slaveFrom = Number(log.discovery.slaveFrom) || 1;
const slaveTo = Number(log.discovery.slaveTo) || 10;
const baud = Number(log.discovery.baud) || 9600;
const parity = textValue(log.discovery.parity, "none");
log.busyAction = mode === "deep" ? "scan_deep" : "scan_quick";
log.error = "";
log.discovery.devices = [];
log.discovery.scanLog = [];
log.discovery.jobId = "";
log.discovery.state = "running";
log.discovery.message = t("Scanning in progress. It may take some minutes.");
appendModbusLog(mode === "deep" ? t("Deep scan started") : t("Quick scan started"), "info");
if (state.activeTab === "modbus") renderActiveTab();
try {
await modbusEnsureSession();
const payload = await fetchJson("/api/modbus/discover", {
method: "POST",
cache: "no-store",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
port: log.port,
family: log.family,
slave_range: [slaveFrom, slaveTo],
baud,
parity,
deep: mode === "deep"
})
});
log.discovery.jobId = textValue(payload.job_id, "");
if (!log.discovery.jobId) {
throw new Error(t("Discovery job was not started"));
}
while (log.discovery.jobId) {
const statusPayload = await fetchJson(`/api/modbus/discover/${encodeURIComponent(log.discovery.jobId)}`, { cache: "no-store" });
log.discovery.state = textValue(statusPayload.state, "running");
log.discovery.message = textValue(statusPayload.message, "");
log.discovery.devices = Array.isArray(statusPayload.devices) ? statusPayload.devices : [];
log.discovery.scanLog = Array.isArray(statusPayload.scan_log) ? statusPayload.scan_log : [];
const progress = statusPayload.progress || {};
log.discovery.checked = Number(progress.checked) || 0;
log.discovery.total = Number(progress.total) || 0;
log.discovery.currentSlave = Number(progress.current_slave) || null;
if (log.discovery.state === "completed") {
appendModbusLog(log.discovery.devices.length ? t("{count} devices found", { count: log.discovery.devices.length }) : t("No Modbus devices found"), log.discovery.devices.length ? "success" : "warn");
break;
}
if (log.discovery.state === "failed") {
throw new Error(statusPayload.error || t("Discovery failed"));
}
if (state.activeTab === "modbus") renderActiveTab();
await new Promise((resolve) => window.setTimeout(resolve, 500));
}
} catch (error) {
log.error = error.message || t("Discovery failed");
log.discovery.state = "failed";
log.discovery.message = log.error;
appendModbusLog(log.error, "error");
showToast("error", log.error);
} finally {
if (log.discovery.state === "completed" && !log.error) {
log.discovery.message = t("Scan completed");
}
log.busyAction = "";
if (state.activeTab === "modbus") renderActiveTab();
}
};
window.__modbusReadConfigFromDiscovery = async function (index) {
window.__modbusSelectDevice(index);
await window.__modbusReadConfig();
};
window.__modbusReadConfig = async function () {
const log = modbusState();
const current = modbusCurrentConnection();
log.busyAction = "read_config";
log.error = "";
if (state.activeTab === "modbus") renderActiveTab();
try {
await modbusEnsureSession();
const payload = await fetchJson("/api/modbus/read-config", {
method: "POST",
cache: "no-store",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
port: log.port,
family: log.family,
slave: current.slave,
baud: current.baud,
parity: current.parity
})
});
log.currentConfig = payload;
log.writeForm.slave = String(payload.current && payload.current.slave || current.slave);
log.writeForm.baud = String(payload.current && payload.current.baud || current.baud);
log.writeForm.parity = textValue(payload.current && payload.current.parity, current.parity);
ingestModbusPayload(payload);
appendModbusLog(t("Current config read completed"), "success");
} catch (error) {
log.error = error.message || t("Failed to read current config");
appendModbusLog(log.error, "error");
showToast("error", log.error);
} finally {
log.busyAction = "";
if (state.activeTab === "modbus") renderActiveTab();
}
};
window.__modbusApplyConfig = async function () {
const log = modbusState();
if (!modbusCanWrite()) return;
log.busyAction = "write_config";
log.error = "";
log.lastWriteResult = null;
log.writeLog = [];
appendModbusWriteLog(t("Write started; backend validation will confirm the final device state"), "info");
appendModbusLog(t("Write started; backend validation will confirm the final device state"), "info");
if (state.activeTab === "modbus") renderActiveTab();
try {
await modbusEnsureSession();
const current = modbusCurrentConnection();
const response = await fetch("/api/modbus/write-config", {
method: "POST",
cache: "no-store",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
port: log.port,
family: log.family,
current: {
slave: Number(current.slave),
baud: Number(current.baud),
parity: current.parity
},
target: {
slave: Number(log.writeForm.slave),
baud: Number(log.writeForm.baud),
parity: log.writeForm.parity
},
strategy: log.writeForm.strategy
})
});
const payload = await response.json().catch(() => ({}));
if (!response.ok && payload.ok !== false) {
throw new Error(payload.error || `HTTP ${response.status}`);
}
log.lastWriteResult = payload;
ingestModbusPayload(payload);
ingestModbusWritePayload(payload);
if (payload.final_detected_config) {
log.selectedDevice = {
port: log.port,
family: log.family,
slave: payload.final_detected_config.slave,
baud: payload.final_detected_config.baud,
parity: payload.final_detected_config.parity
};
if (payload.status === "verified_target" || payload.status === "found_elsewhere") {
await window.__modbusReadConfig();
}
}
const status = textValue(payload.status, "");
const level = payload.ok === true && status === "verified_target"
? "success"
: (status === "found_elsewhere" || status === "write_unconfirmed" ? "warn" : "error");
const message = payload.message || payload.recommended_next_step || t("Configuration write completed");
appendModbusWriteLog(message, level);
appendModbusLog(message, level);
showToast(level, message);
if (payload.ok === false && level === "error") {
log.error = message;
}
} catch (error) {
log.error = error.message || t("Failed to apply Modbus changes");
appendModbusWriteLog(log.error, "error");
appendModbusLog(log.error, "error");
showToast("error", log.error);
} finally {
log.busyAction = "";
if (state.activeTab === "modbus") {
renderActiveTab();
scrollModbusWriteLogToBottom();
}
}
};
window.__modbusReadRegister = async function () {
const log = modbusState();
const current = modbusCurrentConnection();
log.busyAction = "register_read";
log.error = "";
try {
await modbusEnsureSession();
const payload = await fetchJson("/api/modbus/register/read", {
method: "POST",
cache: "no-store",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
port: log.port,
family: log.family,
slave: Number(current.slave),
baud: Number(current.baud),
parity: current.parity,
address: Number(log.registerForm.address),
count: Number(log.registerForm.count),
register_type: log.registerForm.registerType,
decode_mode: log.registerForm.decodeMode
})
});
log.registerForm.lastResult = payload;
ingestModbusPayload(payload);
appendModbusLog(t("Register read completed"), "success");
} catch (error) {
log.error = error.message || t("Register read failed");
appendModbusLog(log.error, "error");
} finally {
log.busyAction = "";
if (state.activeTab === "modbus") renderActiveTab();
}
};
window.__modbusWriteRegister = async function () {
const log = modbusState();
const current = modbusCurrentConnection();
log.busyAction = "register_write";
log.error = "";
try {
await modbusEnsureSession();
const payload = await fetchJson("/api/modbus/register/write", {
method: "POST",
cache: "no-store",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
port: log.port,
family: log.family,
slave: Number(current.slave),
baud: Number(current.baud),
parity: current.parity,
address: Number(log.registerForm.address),
value: Number(log.registerForm.value)
})
});
log.registerForm.lastResult = payload;
ingestModbusPayload(payload);
appendModbusLog(payload.message || t("Register write completed"), "success");
} catch (error) {
log.error = error.message || t("Register write failed");
appendModbusLog(log.error, "error");
} finally {
log.busyAction = "";
if (state.activeTab === "modbus") renderActiveTab();
}
};
nodes.tabs.forEach((button) => { nodes.tabs.forEach((button) => {
button.addEventListener("click", async () => { button.addEventListener("click", async () => {
const nextTab = button.dataset.tab; const nextTab = button.dataset.tab;

View File

@ -85,6 +85,7 @@
<nav class="tabs" aria-label="Primary navigation"> <nav class="tabs" aria-label="Primary navigation">
<button class="tabBtn is-active" type="button" data-tab="health" id="tabHealth">Health</button> <button class="tabBtn is-active" type="button" data-tab="health" id="tabHealth">Health</button>
<button class="tabBtn" type="button" data-tab="network" id="tabNetwork">Network</button> <button class="tabBtn" type="button" data-tab="network" id="tabNetwork">Network</button>
<button class="tabBtn" type="button" data-tab="modbus" id="tabModbus">Modbus</button>
<button class="tabBtn" type="button" data-tab="tscreen" id="tabTscreen">It-Screen</button> <button class="tabBtn" type="button" data-tab="tscreen" id="tabTscreen">It-Screen</button>
<button class="tabBtn" type="button" data-tab="gbox" id="tabGbox">G-Box Instructions and Manual</button> <button class="tabBtn" type="button" data-tab="gbox" id="tabGbox">G-Box Instructions and Manual</button>
</nav> </nav>

View File

@ -0,0 +1,24 @@
{
"family": "iomx_nano_exbd_08_16_12",
"title": "IOMX NANO_ExBd-08/16-12",
"display_name": "IOMX NANO_ExBd-08/16-12",
"transport": {
"protocol": "modbus_rtu",
"default_port": "/dev/ttyS3",
"default_baud": 9600,
"default_parity": "none",
"default_databits": 8,
"default_stopbits": 1,
"scan_baud": [1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200],
"scan_parity": ["none", "even", "odd"],
"zero_based": false
},
"registers": {
"test_read": {
"address": 1,
"count": 1,
"type": "holding"
}
},
"comm_profiles": []
}

View File

@ -0,0 +1,36 @@
{
"family": "ultrasonic_water_meter",
"title": "Ultrasonic Water Flow Meter IOMX WM 214C",
"display_name": "Ultrasonic Water Flow Meter IOMX WM 214C",
"transport": {
"protocol": "modbus_rtu",
"default_port": "/dev/ttyS3",
"default_baud": 9600,
"default_parity": "none",
"default_databits": 8,
"default_stopbits": 1,
"scan_baud": [2400, 4800, 9600],
"scan_parity": ["none", "even", "odd"],
"zero_based": true
},
"registers": {
"test_read": {
"address": 0,
"count": 1,
"type": "holding"
},
"slave_id": {
"address": 1543,
"count": 1,
"type": "holding",
"rw": true
},
"comm_profile": {
"address": 1544,
"count": 1,
"type": "holding",
"rw": true
}
},
"comm_profiles": []
}

View File

@ -28,6 +28,7 @@ PUBLIC_DIR="${APP_DIR}/public"
BACKEND_DIR="${APP_DIR}/backend" BACKEND_DIR="${APP_DIR}/backend"
PROVIDERS_DIR="${APP_DIR}/providers.d" PROVIDERS_DIR="${APP_DIR}/providers.d"
FRONTEND_DIR="${APP_DIR}/frontend" FRONTEND_DIR="${APP_DIR}/frontend"
MODBUS_PROFILES_DIR="${APP_DIR}/modbus_profiles"
SERVICE_NAME="iomatex-console.service" SERVICE_NAME="iomatex-console.service"
LEGACY_SERVICE_NAME="iomatex-webipc.service" LEGACY_SERVICE_NAME="iomatex-webipc.service"
CFG_PATH="/etc/iomatex/console.json" CFG_PATH="/etc/iomatex/console.json"
@ -44,6 +45,7 @@ STAGE_PUBLIC_DIR="${STAGE_DIR}/public"
STAGE_BACKEND_DIR="${STAGE_DIR}/backend" STAGE_BACKEND_DIR="${STAGE_DIR}/backend"
STAGE_PROVIDERS_DIR="${STAGE_DIR}/providers.d" STAGE_PROVIDERS_DIR="${STAGE_DIR}/providers.d"
STAGE_FRONTEND_DIR="${STAGE_DIR}/frontend" STAGE_FRONTEND_DIR="${STAGE_DIR}/frontend"
STAGE_MODBUS_PROFILES_DIR="${STAGE_DIR}/modbus_profiles"
copy_tree() { copy_tree() {
local src="$1" local src="$1"
@ -72,7 +74,7 @@ rollback_deploy() {
wait_for_local_http() { wait_for_local_http() {
local attempt local attempt
for attempt in $(seq 1 15); do for attempt in $(seq 1 30); do
if ! systemctl is-active --quiet "${SERVICE_NAME}"; then if ! systemctl is-active --quiet "${SERVICE_NAME}"; then
sleep 1 sleep 1
continue continue
@ -85,7 +87,7 @@ wait_for_local_http() {
import sys import sys
import urllib.request import urllib.request
try: try:
with urllib.request.urlopen("http://127.0.0.1/api/status", timeout=2) as response: with urllib.request.urlopen("http://127.0.0.1/api/status", timeout=5) as response:
sys.exit(0 if response.status == 200 else 1) sys.exit(0 if response.status == 200 else 1)
except Exception: except Exception:
sys.exit(1) sys.exit(1)
@ -135,6 +137,9 @@ step "Validate source tree"
for path in \ for path in \
"$SRC_ROOT/backend/app.py" \ "$SRC_ROOT/backend/app.py" \
"$SRC_ROOT/backend/itscreen_registration.py" \ "$SRC_ROOT/backend/itscreen_registration.py" \
"$SRC_ROOT/backend/modbus_backend.py" \
"$SRC_ROOT/modbus_profiles/ultrasonic_water_meter.json" \
"$SRC_ROOT/modbus_profiles/iomx_nano_exbd_08_16_12.json" \
"$SRC_ROOT/frontend/index.html" \ "$SRC_ROOT/frontend/index.html" \
"$SRC_ROOT/frontend/console.i18n.js" \ "$SRC_ROOT/frontend/console.i18n.js" \
"$SRC_ROOT/frontend/console.js" \ "$SRC_ROOT/frontend/console.js" \
@ -148,7 +153,7 @@ done
step "Ensure runtime packages exist" step "Ensure runtime packages exist"
apt-get update apt-get update
apt-get install -y python3 python3-pil python3-paho-mqtt network-manager iw apt-get install -y python3 python3-pil python3-paho-mqtt network-manager iw mbpoll psmisc
python3 --version python3 --version
echo "Skip setcap: service runs as root and can bind port 80 without extra capabilities" echo "Skip setcap: service runs as root and can bind port 80 without extra capabilities"
@ -163,7 +168,7 @@ if [ -d "$LEGACY_APP_DIR" ]; then
mv "$LEGACY_APP_DIR" "$LEGACY_PREV_DIR" mv "$LEGACY_APP_DIR" "$LEGACY_PREV_DIR"
fi fi
rm -rf "$STAGE_DIR" rm -rf "$STAGE_DIR"
mkdir -p "$STAGE_DIR" "$STAGE_PUBLIC_DIR" "$STAGE_BACKEND_DIR" "$STAGE_PROVIDERS_DIR" "$STAGE_FRONTEND_DIR" mkdir -p "$STAGE_DIR" "$STAGE_PUBLIC_DIR" "$STAGE_BACKEND_DIR" "$STAGE_PROVIDERS_DIR" "$STAGE_FRONTEND_DIR" "$STAGE_MODBUS_PROFILES_DIR"
cat > "$CFG_PATH" <<JSON cat > "$CFG_PATH" <<JSON
{ {
@ -176,6 +181,7 @@ JSON
step "Install console core files" step "Install console core files"
copy_tree "$SRC_ROOT/backend" "$STAGE_BACKEND_DIR" copy_tree "$SRC_ROOT/backend" "$STAGE_BACKEND_DIR"
copy_tree "$SRC_ROOT/frontend" "$STAGE_FRONTEND_DIR" copy_tree "$SRC_ROOT/frontend" "$STAGE_FRONTEND_DIR"
copy_tree "$SRC_ROOT/modbus_profiles" "$STAGE_MODBUS_PROFILES_DIR"
install -m 0644 "$SRC_ROOT/frontend/index.html" "$STAGE_PUBLIC_DIR/index.html" install -m 0644 "$SRC_ROOT/frontend/index.html" "$STAGE_PUBLIC_DIR/index.html"
install -m 0644 "$SRC_ROOT/frontend/console.i18n.js" "$STAGE_PUBLIC_DIR/console.i18n.js" install -m 0644 "$SRC_ROOT/frontend/console.i18n.js" "$STAGE_PUBLIC_DIR/console.i18n.js"
install -m 0644 "$SRC_ROOT/frontend/console.js" "$STAGE_PUBLIC_DIR/console.js" install -m 0644 "$SRC_ROOT/frontend/console.js" "$STAGE_PUBLIC_DIR/console.js"
@ -184,11 +190,14 @@ copy_tree "$SRC_ROOT/providers" "$STAGE_PROVIDERS_DIR"
rm -rf "$STAGE_PROVIDERS_DIR/__pycache__" "$STAGE_BACKEND_DIR/__pycache__" rm -rf "$STAGE_PROVIDERS_DIR/__pycache__" "$STAGE_BACKEND_DIR/__pycache__"
require_file "$STAGE_BACKEND_DIR/app.py" require_file "$STAGE_BACKEND_DIR/app.py"
require_file "$STAGE_BACKEND_DIR/itscreen_registration.py" require_file "$STAGE_BACKEND_DIR/itscreen_registration.py"
require_file "$STAGE_BACKEND_DIR/modbus_backend.py"
require_file "$STAGE_FRONTEND_DIR/index.html" require_file "$STAGE_FRONTEND_DIR/index.html"
require_file "$STAGE_FRONTEND_DIR/console.i18n.js" require_file "$STAGE_FRONTEND_DIR/console.i18n.js"
require_file "$STAGE_FRONTEND_DIR/console.js" require_file "$STAGE_FRONTEND_DIR/console.js"
require_file "$STAGE_FRONTEND_DIR/console.css" require_file "$STAGE_FRONTEND_DIR/console.css"
require_file "$STAGE_PROVIDERS_DIR/00_core_services.py" require_file "$STAGE_PROVIDERS_DIR/00_core_services.py"
require_file "$STAGE_MODBUS_PROFILES_DIR/ultrasonic_water_meter.json"
require_file "$STAGE_MODBUS_PROFILES_DIR/iomx_nano_exbd_08_16_12.json"
require_file "$SRC_GBOX" require_file "$SRC_GBOX"
step "Generate logo and favicon" step "Generate logo and favicon"
@ -240,7 +249,7 @@ remove_if_exists /usr/local/sbin/iomatex-mdns-alias
remove_if_exists /etc/systemd/system/iomatex-mdns-alias.service remove_if_exists /etc/systemd/system/iomatex-mdns-alias.service
step "Validate and restart" step "Validate and restart"
python3 -m py_compile "$STAGE_BACKEND_DIR/app.py" "$STAGE_BACKEND_DIR/itscreen_registration.py" "$STAGE_PROVIDERS_DIR/00_core_services.py" python3 -m py_compile "$STAGE_BACKEND_DIR/app.py" "$STAGE_BACKEND_DIR/itscreen_registration.py" "$STAGE_BACKEND_DIR/modbus_backend.py" "$STAGE_PROVIDERS_DIR/00_core_services.py"
require_file "$STAGE_PUBLIC_DIR/index.html" require_file "$STAGE_PUBLIC_DIR/index.html"
require_file "$STAGE_PUBLIC_DIR/console.js" require_file "$STAGE_PUBLIC_DIR/console.js"
require_file "$STAGE_PUBLIC_DIR/console.css" require_file "$STAGE_PUBLIC_DIR/console.css"
@ -251,10 +260,13 @@ fi
mv "$STAGE_DIR" "$APP_DIR" mv "$STAGE_DIR" "$APP_DIR"
require_file "$BACKEND_DIR/app.py" require_file "$BACKEND_DIR/app.py"
require_file "$BACKEND_DIR/itscreen_registration.py" require_file "$BACKEND_DIR/itscreen_registration.py"
require_file "$BACKEND_DIR/modbus_backend.py"
require_file "$FRONTEND_DIR/index.html" require_file "$FRONTEND_DIR/index.html"
require_file "$FRONTEND_DIR/console.js" require_file "$FRONTEND_DIR/console.js"
require_file "$FRONTEND_DIR/console.css" require_file "$FRONTEND_DIR/console.css"
require_file "$PROVIDERS_DIR/00_core_services.py" require_file "$PROVIDERS_DIR/00_core_services.py"
require_file "$MODBUS_PROFILES_DIR/ultrasonic_water_meter.json"
require_file "$MODBUS_PROFILES_DIR/iomx_nano_exbd_08_16_12.json"
systemctl daemon-reload systemctl daemon-reload
systemctl_try disable --now iomatex-mdns-alias.service systemctl_try disable --now iomatex-mdns-alias.service
if ! systemctl enable --now "${SERVICE_NAME}"; then if ! systemctl enable --now "${SERVICE_NAME}"; then
@ -285,6 +297,7 @@ echo "Install dir: ${APP_DIR}"
echo "Frontend dir: ${FRONTEND_DIR}" echo "Frontend dir: ${FRONTEND_DIR}"
echo "Providers dir: ${PROVIDERS_DIR}" echo "Providers dir: ${PROVIDERS_DIR}"
echo "Public dir: ${PUBLIC_DIR}" echo "Public dir: ${PUBLIC_DIR}"
echo "Modbus profiles dir: ${MODBUS_PROFILES_DIR}"
echo "Config: ${CFG_PATH}" echo "Config: ${CFG_PATH}"
echo "Previous install backup: ${PREV_DIR}" echo "Previous install backup: ${PREV_DIR}"
echo "Legacy backup: ${LEGACY_PREV_DIR}" echo "Legacy backup: ${LEGACY_PREV_DIR}"