3ee0cae31e
v1.5.0 shipped the forwarder module + INI keys but the settings
dialog wasn't extended, so the only way operators could enable
forwarding was hand-editing config.ini. This adds a sixth tab
("SFM Forward") with:
- Forward events to SFM checkbox
- SFM Server URL entry + Test button (GETs /health)
- Forward Interval (sec) spinbox
- Quiescence (sec) spinbox
- Missing-Report Grace spinbox
- HTTP Timeout spinbox
- State File entry + Browse...
Save-time guard: enabling the forwarder without a URL raises a
validation error rather than silently saving a non-functional
config.
Patch release — same on-disk INI schema, no config migration.
753 lines
30 KiB
Python
753 lines
30 KiB
Python
"""
|
|
Series 3 Watcher — Settings Dialog v1.5.1
|
|
|
|
Provides a Tkinter settings dialog that doubles as a first-run wizard.
|
|
|
|
Public API:
|
|
show_dialog(config_path, wizard=False) -> bool
|
|
Returns True if the user saved, False if they cancelled.
|
|
|
|
Python 3.8 compatible — no walrus operators, no f-string = specifier,
|
|
no match statements, no 3.9+ syntax.
|
|
No external dependencies beyond stdlib + tkinter.
|
|
"""
|
|
|
|
import os
|
|
import configparser
|
|
import tkinter as tk
|
|
from tkinter import ttk, filedialog, messagebox
|
|
from socket import gethostname
|
|
|
|
|
|
# --------------- Defaults (mirror config-template.ini) ---------------
|
|
|
|
DEFAULTS = {
|
|
"API_ENABLED": "true",
|
|
"API_URL": "",
|
|
"API_INTERVAL_SECONDS": "300",
|
|
"SOURCE_ID": "", # empty = use hostname at runtime
|
|
"SOURCE_TYPE": "series3_watcher",
|
|
"SERIES3_PATH": r"C:\Blastware 10\Event\autocall home",
|
|
"MAX_EVENT_AGE_DAYS": "365",
|
|
"SCAN_INTERVAL_SECONDS":"300",
|
|
"MLG_HEADER_BYTES": "2048",
|
|
"ENABLE_LOGGING": "true",
|
|
"LOG_FILE": os.path.join(
|
|
os.environ.get("LOCALAPPDATA") or os.environ.get("APPDATA") or "C:\\",
|
|
"Series3Watcher", "agent_logs", "series3_watcher.log"
|
|
),
|
|
"LOG_RETENTION_DAYS": "30",
|
|
|
|
# Auto-updater
|
|
"UPDATE_SOURCE": "gitea",
|
|
"UPDATE_URL": "",
|
|
|
|
# SFM event forwarder (default-off; existing 1.4.x deployments
|
|
# don't change behaviour after auto-update until an operator
|
|
# opts in by setting SFM_URL + flipping SFM_FORWARD_ENABLED).
|
|
"SFM_FORWARD_ENABLED": "false",
|
|
"SFM_URL": "",
|
|
"SFM_FORWARD_INTERVAL_SECONDS": "60",
|
|
"SFM_QUIESCENCE_SECONDS": "5",
|
|
"SFM_MISSING_REPORT_GRACE_SECONDS": "60",
|
|
"SFM_HTTP_TIMEOUT": "60",
|
|
"SFM_STATE_FILE": "",
|
|
}
|
|
|
|
|
|
# --------------- Config I/O ---------------
|
|
|
|
def _load_config(config_path):
|
|
"""
|
|
Load existing config.ini. Returns a flat dict of string values.
|
|
Falls back to DEFAULTS for any missing key.
|
|
"""
|
|
values = dict(DEFAULTS)
|
|
if not os.path.exists(config_path):
|
|
return values
|
|
|
|
cp = configparser.ConfigParser(inline_comment_prefixes=(";", "#"))
|
|
cp.optionxform = str
|
|
try:
|
|
cp.read(config_path, encoding="utf-8")
|
|
except Exception:
|
|
return values
|
|
|
|
# Accept either [agent] section or a bare file
|
|
section = None
|
|
if cp.has_section("agent"):
|
|
section = "agent"
|
|
elif cp.sections():
|
|
section = cp.sections()[0]
|
|
|
|
if section:
|
|
for k in DEFAULTS:
|
|
if cp.has_option(section, k):
|
|
values[k] = cp.get(section, k).strip()
|
|
|
|
return values
|
|
|
|
|
|
def _save_config(config_path, values):
|
|
"""Write all values to config_path under [agent] section."""
|
|
cp = configparser.ConfigParser()
|
|
cp.optionxform = str
|
|
cp["agent"] = {}
|
|
for k, v in values.items():
|
|
cp["agent"][k] = v
|
|
|
|
config_dir = os.path.dirname(config_path)
|
|
if config_dir and not os.path.exists(config_dir):
|
|
os.makedirs(config_dir)
|
|
|
|
with open(config_path, "w", encoding="utf-8") as f:
|
|
cp.write(f)
|
|
|
|
|
|
# --------------- Spinbox helper ---------------
|
|
|
|
def _make_spinbox(parent, from_, to, width=8):
|
|
"""Create a ttk.Spinbox; fall back to tk.Spinbox on older ttk."""
|
|
try:
|
|
sb = ttk.Spinbox(parent, from_=from_, to=to, width=width)
|
|
except AttributeError:
|
|
# ttk.Spinbox added in Python 3.7 but not available everywhere
|
|
sb = tk.Spinbox(parent, from_=from_, to=to, width=width)
|
|
return sb
|
|
|
|
|
|
# --------------- Field helpers ---------------
|
|
|
|
def _add_label_entry(frame, row, label_text, var, hint=None, readonly=False):
|
|
"""Add a label + entry row to a grid frame. Returns the Entry widget."""
|
|
tk.Label(frame, text=label_text, anchor="w").grid(
|
|
row=row, column=0, sticky="w", padx=(8, 4), pady=4
|
|
)
|
|
state = "readonly" if readonly else "normal"
|
|
entry = ttk.Entry(frame, textvariable=var, width=42, state=state)
|
|
entry.grid(row=row, column=1, sticky="ew", padx=(0, 8), pady=4)
|
|
if hint and not var.get():
|
|
# Show placeholder hint in grey; clear on focus
|
|
entry.config(foreground="grey")
|
|
entry.insert(0, hint)
|
|
|
|
def _on_focus_in(event, e=entry, h=hint, v=var):
|
|
if e.get() == h:
|
|
e.delete(0, tk.END)
|
|
e.config(foreground="black")
|
|
|
|
def _on_focus_out(event, e=entry, h=hint, v=var):
|
|
if not e.get():
|
|
e.config(foreground="grey")
|
|
e.insert(0, h)
|
|
v.set("")
|
|
|
|
entry.bind("<FocusIn>", _on_focus_in)
|
|
entry.bind("<FocusOut>", _on_focus_out)
|
|
return entry
|
|
|
|
|
|
def _add_label_spinbox(frame, row, label_text, var, from_, to):
|
|
"""Add a label + spinbox row to a grid frame. Returns the Spinbox widget."""
|
|
tk.Label(frame, text=label_text, anchor="w").grid(
|
|
row=row, column=0, sticky="w", padx=(8, 4), pady=4
|
|
)
|
|
sb = _make_spinbox(frame, from_=from_, to=to, width=8)
|
|
sb.grid(row=row, column=1, sticky="w", padx=(0, 8), pady=4)
|
|
sb.delete(0, tk.END)
|
|
sb.insert(0, var.get())
|
|
|
|
def _on_change(*args):
|
|
var.set(sb.get())
|
|
|
|
sb.config(command=_on_change)
|
|
sb.bind("<KeyRelease>", _on_change)
|
|
return sb
|
|
|
|
|
|
def _add_label_check(frame, row, label_text, var):
|
|
"""Add a checkbox row to a grid frame."""
|
|
cb = ttk.Checkbutton(frame, text=label_text, variable=var)
|
|
cb.grid(row=row, column=0, columnspan=2, sticky="w", padx=(8, 8), pady=4)
|
|
return cb
|
|
|
|
|
|
def _add_label_browse_entry(frame, row, label_text, var, browse_fn):
|
|
"""Add a label + entry + Browse button row."""
|
|
tk.Label(frame, text=label_text, anchor="w").grid(
|
|
row=row, column=0, sticky="w", padx=(8, 4), pady=4
|
|
)
|
|
inner = tk.Frame(frame)
|
|
inner.grid(row=row, column=1, sticky="ew", padx=(0, 8), pady=4)
|
|
inner.columnconfigure(0, weight=1)
|
|
|
|
entry = ttk.Entry(inner, textvariable=var, width=36)
|
|
entry.grid(row=0, column=0, sticky="ew")
|
|
btn = ttk.Button(inner, text="Browse...", command=browse_fn, width=9)
|
|
btn.grid(row=0, column=1, padx=(4, 0))
|
|
return entry
|
|
|
|
|
|
# --------------- Main dialog class ---------------
|
|
|
|
class SettingsDialog:
|
|
def __init__(self, parent, config_path, wizard=False):
|
|
self.config_path = config_path
|
|
self.wizard = wizard
|
|
self.saved = False
|
|
|
|
self.root = parent
|
|
if wizard:
|
|
self.root.title("Series 3 Watcher — Setup")
|
|
else:
|
|
self.root.title("Series 3 Watcher — Settings")
|
|
self.root.resizable(False, False)
|
|
|
|
# Center on screen
|
|
self.root.update_idletasks()
|
|
|
|
self._values = _load_config(config_path)
|
|
self._build_vars()
|
|
self._build_ui()
|
|
|
|
# Make dialog modal
|
|
self.root.grab_set()
|
|
self.root.protocol("WM_DELETE_WINDOW", self._on_cancel)
|
|
|
|
# --- Variable setup ---
|
|
|
|
def _build_vars(self):
|
|
v = self._values
|
|
|
|
# Connection
|
|
self.var_api_enabled = tk.BooleanVar(value=v["API_ENABLED"].lower() in ("1","true","yes","on"))
|
|
# Strip the fixed endpoint suffix so the dialog shows just the base URL
|
|
_raw_url = v["API_URL"]
|
|
_suffix = "/api/series3/heartbeat"
|
|
if _raw_url.endswith(_suffix):
|
|
_raw_url = _raw_url[:-len(_suffix)]
|
|
self.var_api_url = tk.StringVar(value=_raw_url)
|
|
self.var_api_interval = tk.StringVar(value=v["API_INTERVAL_SECONDS"])
|
|
self.var_source_id = tk.StringVar(value=v["SOURCE_ID"])
|
|
self.var_source_type = tk.StringVar(value=v["SOURCE_TYPE"])
|
|
|
|
# Paths
|
|
self.var_series3_path = tk.StringVar(value=v["SERIES3_PATH"])
|
|
self.var_max_event_age_days = tk.StringVar(value=v["MAX_EVENT_AGE_DAYS"])
|
|
self.var_log_file = tk.StringVar(value=v["LOG_FILE"])
|
|
|
|
# Scanning
|
|
self.var_scan_interval = tk.StringVar(value=v["SCAN_INTERVAL_SECONDS"])
|
|
self.var_mlg_header_bytes = tk.StringVar(value=v["MLG_HEADER_BYTES"])
|
|
|
|
# Logging
|
|
self.var_enable_logging = tk.BooleanVar(value=v["ENABLE_LOGGING"].lower() in ("1","true","yes","on"))
|
|
self.var_log_retention_days = tk.StringVar(value=v["LOG_RETENTION_DAYS"])
|
|
|
|
# Updates
|
|
self.var_update_source = tk.StringVar(value=v["UPDATE_SOURCE"].lower() if v["UPDATE_SOURCE"].lower() in ("gitea", "url", "disabled") else "gitea")
|
|
self.var_update_url = tk.StringVar(value=v["UPDATE_URL"])
|
|
|
|
# SFM event forwarder
|
|
self.var_sfm_enabled = tk.BooleanVar(
|
|
value=v["SFM_FORWARD_ENABLED"].lower() in ("1", "true", "yes", "on"))
|
|
self.var_sfm_url = tk.StringVar(value=v["SFM_URL"])
|
|
self.var_sfm_forward_interval = tk.StringVar(value=v["SFM_FORWARD_INTERVAL_SECONDS"])
|
|
self.var_sfm_quiescence = tk.StringVar(value=v["SFM_QUIESCENCE_SECONDS"])
|
|
self.var_sfm_missing_report_grace = tk.StringVar(value=v["SFM_MISSING_REPORT_GRACE_SECONDS"])
|
|
self.var_sfm_http_timeout = tk.StringVar(value=v["SFM_HTTP_TIMEOUT"])
|
|
self.var_sfm_state_file = tk.StringVar(value=v["SFM_STATE_FILE"])
|
|
|
|
# --- UI construction ---
|
|
|
|
def _build_ui(self):
|
|
outer = tk.Frame(self.root, padx=10, pady=8)
|
|
outer.pack(fill="both", expand=True)
|
|
|
|
if self.wizard:
|
|
welcome = (
|
|
"Welcome to Series 3 Watcher!\n\n"
|
|
"No configuration file was found. Please review the settings below\n"
|
|
"and click \"Save & Start\" when you are ready."
|
|
)
|
|
lbl = tk.Label(
|
|
outer, text=welcome, justify="left",
|
|
wraplength=460, fg="#1a5276", font=("TkDefaultFont", 9, "bold"),
|
|
)
|
|
lbl.pack(fill="x", pady=(0, 8))
|
|
|
|
# Notebook
|
|
nb = ttk.Notebook(outer)
|
|
nb.pack(fill="both", expand=True)
|
|
|
|
self._build_tab_connection(nb)
|
|
self._build_tab_paths(nb)
|
|
self._build_tab_scanning(nb)
|
|
self._build_tab_logging(nb)
|
|
self._build_tab_updates(nb)
|
|
self._build_tab_sfm(nb)
|
|
|
|
# Buttons
|
|
btn_frame = tk.Frame(outer)
|
|
btn_frame.pack(fill="x", pady=(10, 0))
|
|
|
|
save_label = "Save & Start" if self.wizard else "Save"
|
|
btn_save = ttk.Button(btn_frame, text=save_label, command=self._on_save, width=14)
|
|
btn_save.pack(side="right", padx=(4, 0))
|
|
|
|
btn_cancel = ttk.Button(btn_frame, text="Cancel", command=self._on_cancel, width=10)
|
|
btn_cancel.pack(side="right")
|
|
|
|
def _tab_frame(self, nb, title):
|
|
"""Create a new tab in nb, return a scrollable inner frame."""
|
|
outer = tk.Frame(nb, padx=4, pady=4)
|
|
nb.add(outer, text=title)
|
|
outer.columnconfigure(1, weight=1)
|
|
return outer
|
|
|
|
def _build_tab_connection(self, nb):
|
|
f = self._tab_frame(nb, "Connection")
|
|
|
|
_add_label_check(f, 0, "API Enabled", self.var_api_enabled)
|
|
|
|
# URL row — entry + Test button in an inner frame
|
|
tk.Label(f, text="Terra-View URL", anchor="w").grid(
|
|
row=1, column=0, sticky="w", padx=(8, 4), pady=4
|
|
)
|
|
url_frame = tk.Frame(f)
|
|
url_frame.grid(row=1, column=1, sticky="ew", padx=(0, 8), pady=4)
|
|
url_frame.columnconfigure(0, weight=1)
|
|
|
|
url_entry = ttk.Entry(url_frame, textvariable=self.var_api_url, width=32)
|
|
url_entry.grid(row=0, column=0, sticky="ew")
|
|
|
|
# Placeholder hint behaviour
|
|
_hint = "http://192.168.x.x:8000"
|
|
if not self.var_api_url.get():
|
|
url_entry.config(foreground="grey")
|
|
url_entry.insert(0, _hint)
|
|
def _on_focus_in(e):
|
|
if url_entry.get() == _hint:
|
|
url_entry.delete(0, tk.END)
|
|
url_entry.config(foreground="black")
|
|
def _on_focus_out(e):
|
|
if not url_entry.get():
|
|
url_entry.config(foreground="grey")
|
|
url_entry.insert(0, _hint)
|
|
self.var_api_url.set("")
|
|
url_entry.bind("<FocusIn>", _on_focus_in)
|
|
url_entry.bind("<FocusOut>", _on_focus_out)
|
|
|
|
self._test_btn = ttk.Button(url_frame, text="Test", width=6,
|
|
command=self._test_connection)
|
|
self._test_btn.grid(row=0, column=1, padx=(4, 0))
|
|
|
|
self._test_status = tk.Label(url_frame, text="", anchor="w", width=20)
|
|
self._test_status.grid(row=0, column=2, padx=(6, 0))
|
|
|
|
_add_label_spinbox(f, 2, "API Interval (sec)", self.var_api_interval, 30, 3600)
|
|
|
|
source_id_hint = "Defaults to hostname ({})".format(gethostname())
|
|
_add_label_entry(f, 3, "Source ID", self.var_source_id, hint=source_id_hint)
|
|
|
|
_add_label_entry(f, 4, "Source Type", self.var_source_type, readonly=True)
|
|
|
|
def _test_connection(self):
|
|
"""POST a minimal ping to the Terra-View heartbeat endpoint and show result."""
|
|
import urllib.request
|
|
import urllib.error
|
|
|
|
self._test_status.config(text="Testing...", foreground="grey")
|
|
self._test_btn.config(state="disabled")
|
|
self.root.update_idletasks()
|
|
|
|
raw = self.var_api_url.get().strip()
|
|
if not raw or raw == "http://192.168.x.x:8000":
|
|
self._test_status.config(text="Enter a URL first", foreground="orange")
|
|
self._test_btn.config(state="normal")
|
|
return
|
|
|
|
url = raw.rstrip("/") + "/health"
|
|
|
|
try:
|
|
req = urllib.request.Request(url)
|
|
with urllib.request.urlopen(req, timeout=5) as resp:
|
|
if resp.status == 200:
|
|
self._test_status.config(text="Connected!", foreground="green")
|
|
else:
|
|
self._test_status.config(
|
|
text="HTTP {}".format(resp.status), foreground="orange"
|
|
)
|
|
except urllib.error.URLError as e:
|
|
reason = str(e.reason) if hasattr(e, "reason") else str(e)
|
|
self._test_status.config(text="Failed: {}".format(reason[:30]), foreground="red")
|
|
except Exception as e:
|
|
self._test_status.config(text="Error: {}".format(str(e)[:30]), foreground="red")
|
|
finally:
|
|
self._test_btn.config(state="normal")
|
|
|
|
def _build_tab_paths(self, nb):
|
|
f = self._tab_frame(nb, "Paths")
|
|
|
|
def browse_series3():
|
|
d = filedialog.askdirectory(
|
|
title="Select Blastware Event Folder",
|
|
initialdir=self.var_series3_path.get() or "C:\\",
|
|
)
|
|
if d:
|
|
self.var_series3_path.set(d.replace("/", "\\"))
|
|
|
|
_add_label_browse_entry(f, 0, "Series3 Path", self.var_series3_path, browse_series3)
|
|
_add_label_spinbox(f, 1, "Max Event Age (days)", self.var_max_event_age_days, 1, 3650)
|
|
|
|
def browse_log():
|
|
p = filedialog.asksaveasfilename(
|
|
title="Select Log File",
|
|
defaultextension=".log",
|
|
filetypes=[("Log files", "*.log"), ("Text files", "*.txt"), ("All files", "*.*")],
|
|
initialfile=os.path.basename(self.var_log_file.get() or "series3_watcher.log"),
|
|
initialdir=os.path.dirname(self.var_log_file.get() or "C:\\"),
|
|
)
|
|
if p:
|
|
self.var_log_file.set(p.replace("/", "\\"))
|
|
|
|
_add_label_browse_entry(f, 2, "Log File", self.var_log_file, browse_log)
|
|
|
|
def _build_tab_scanning(self, nb):
|
|
f = self._tab_frame(nb, "Scanning")
|
|
_add_label_spinbox(f, 0, "Scan Interval (sec)", self.var_scan_interval, 10, 3600)
|
|
_add_label_spinbox(f, 1, "MLG Header Bytes", self.var_mlg_header_bytes, 256, 65536)
|
|
|
|
def _build_tab_logging(self, nb):
|
|
f = self._tab_frame(nb, "Logging")
|
|
_add_label_check(f, 0, "Enable Logging", self.var_enable_logging)
|
|
_add_label_spinbox(f, 1, "Log Retention (days)", self.var_log_retention_days, 1, 365)
|
|
|
|
def _build_tab_updates(self, nb):
|
|
f = self._tab_frame(nb, "Updates")
|
|
|
|
tk.Label(
|
|
f,
|
|
text="Auto-Update Source",
|
|
anchor="w",
|
|
).grid(row=0, column=0, sticky="w", padx=(8, 4), pady=(8, 2))
|
|
|
|
radio_frame = tk.Frame(f)
|
|
radio_frame.grid(row=0, column=1, sticky="w", padx=(0, 8), pady=(8, 2))
|
|
|
|
rb_gitea = ttk.Radiobutton(
|
|
radio_frame, text="Gitea (default)",
|
|
variable=self.var_update_source, value="gitea",
|
|
command=self._on_update_source_change,
|
|
)
|
|
rb_gitea.grid(row=0, column=0, sticky="w", padx=(0, 12))
|
|
|
|
rb_url = ttk.Radiobutton(
|
|
radio_frame, text="Custom URL",
|
|
variable=self.var_update_source, value="url",
|
|
command=self._on_update_source_change,
|
|
)
|
|
rb_url.grid(row=0, column=1, sticky="w", padx=(0, 12))
|
|
|
|
rb_disabled = ttk.Radiobutton(
|
|
radio_frame, text="Disabled",
|
|
variable=self.var_update_source, value="disabled",
|
|
command=self._on_update_source_change,
|
|
)
|
|
rb_disabled.grid(row=0, column=2, sticky="w")
|
|
|
|
tk.Label(f, text="Update Server URL", anchor="w").grid(
|
|
row=1, column=0, sticky="w", padx=(8, 4), pady=4
|
|
)
|
|
self._update_url_entry = ttk.Entry(f, textvariable=self.var_update_url, width=42)
|
|
self._update_url_entry.grid(row=1, column=1, sticky="ew", padx=(0, 8), pady=4)
|
|
|
|
hint_text = (
|
|
"Gitea: checks the Gitea release page automatically every 5 minutes.\n"
|
|
"Custom URL: fetches version.txt and series3-watcher.exe from a web\n"
|
|
"server — use when Gitea is not reachable (e.g. terra-view URL).\n"
|
|
"Disabled: no automatic update checks. Remote push from terra-view\n"
|
|
"still works when disabled."
|
|
)
|
|
tk.Label(f, text=hint_text, justify="left", fg="#555555",
|
|
wraplength=380).grid(
|
|
row=2, column=0, columnspan=2, sticky="w", padx=(8, 8), pady=(4, 8)
|
|
)
|
|
|
|
# Set initial state of URL entry
|
|
self._on_update_source_change()
|
|
|
|
def _on_update_source_change(self):
|
|
"""Enable/disable the URL entry based on selected update source."""
|
|
if self.var_update_source.get() == "url":
|
|
self._update_url_entry.config(state="normal")
|
|
else:
|
|
self._update_url_entry.config(state="disabled")
|
|
|
|
# ──────────────────────────────────────────────────────────────────
|
|
# SFM Forward tab
|
|
# ──────────────────────────────────────────────────────────────────
|
|
|
|
def _build_tab_sfm(self, nb):
|
|
"""Configure the SFM event forwarder.
|
|
|
|
When enabled, every Blastware event binary in the watch folder
|
|
(plus its paired .TXT report when present) is POSTed to an SFM
|
|
server's /db/import/blastware_file endpoint. Default-off so
|
|
existing 1.4.x deployments don't change behaviour after an
|
|
auto-update — operator opts in by setting the URL and flipping
|
|
the checkbox.
|
|
"""
|
|
f = self._tab_frame(nb, "SFM Forward")
|
|
|
|
_add_label_check(f, 0, "Forward events to SFM", self.var_sfm_enabled)
|
|
|
|
# SFM URL row — entry + Test button (mirrors the Connection tab's pattern)
|
|
tk.Label(f, text="SFM Server URL", anchor="w").grid(
|
|
row=1, column=0, sticky="w", padx=(8, 4), pady=4
|
|
)
|
|
url_frame = tk.Frame(f)
|
|
url_frame.grid(row=1, column=1, sticky="ew", padx=(0, 8), pady=4)
|
|
url_frame.columnconfigure(0, weight=1)
|
|
|
|
sfm_entry = ttk.Entry(url_frame, textvariable=self.var_sfm_url, width=32)
|
|
sfm_entry.grid(row=0, column=0, sticky="ew")
|
|
|
|
self._sfm_test_btn = ttk.Button(
|
|
url_frame, text="Test", width=6, command=self._test_sfm_connection,
|
|
)
|
|
self._sfm_test_btn.grid(row=0, column=1, padx=(4, 0))
|
|
|
|
self._sfm_test_status = tk.Label(url_frame, text="", anchor="w", width=20)
|
|
self._sfm_test_status.grid(row=0, column=2, padx=(6, 0))
|
|
|
|
_add_label_spinbox(f, 2, "Forward Interval (sec)", self.var_sfm_forward_interval, 5, 3600)
|
|
_add_label_spinbox(f, 3, "Quiescence (sec)", self.var_sfm_quiescence, 1, 60)
|
|
_add_label_spinbox(f, 4, "Missing-Report Grace (sec)", self.var_sfm_missing_report_grace, 0, 600)
|
|
_add_label_spinbox(f, 5, "HTTP Timeout (sec)", self.var_sfm_http_timeout, 5, 600)
|
|
|
|
tk.Label(f, text="State File", anchor="w").grid(
|
|
row=6, column=0, sticky="w", padx=(8, 4), pady=4
|
|
)
|
|
state_frame = tk.Frame(f)
|
|
state_frame.grid(row=6, column=1, sticky="ew", padx=(0, 8), pady=4)
|
|
state_frame.columnconfigure(0, weight=1)
|
|
|
|
state_entry = ttk.Entry(state_frame, textvariable=self.var_sfm_state_file, width=32)
|
|
state_entry.grid(row=0, column=0, sticky="ew")
|
|
|
|
def _browse_state():
|
|
path = filedialog.asksaveasfilename(
|
|
title="SFM forward-state file",
|
|
defaultextension=".json",
|
|
filetypes=[("JSON", "*.json"), ("All Files", "*.*")],
|
|
initialfile="sfm_forwarded.json",
|
|
)
|
|
if path:
|
|
self.var_sfm_state_file.set(path)
|
|
|
|
ttk.Button(state_frame, text="Browse...", width=10, command=_browse_state).grid(
|
|
row=0, column=1, padx=(4, 0)
|
|
)
|
|
|
|
hint_text = (
|
|
"Forwards every Blastware event binary (and its paired .TXT report)\n"
|
|
"to an SFM server, where the report is parsed for searchable\n"
|
|
"per-channel stats: PPV, ZC Freq, Time of Peak, Peak Acceleration,\n"
|
|
"Peak Displacement, sensor self-check, monitor log.\n\n"
|
|
"Idempotent: forwarded files are tracked by sha256 in the state\n"
|
|
"file; restarts and re-scans never re-POST. Leave State File blank\n"
|
|
"to default to <log dir>/sfm_forwarded.json."
|
|
)
|
|
tk.Label(f, text=hint_text, justify="left", fg="#555555", wraplength=380).grid(
|
|
row=7, column=0, columnspan=2, sticky="w", padx=(8, 8), pady=(8, 4)
|
|
)
|
|
|
|
def _test_sfm_connection(self):
|
|
"""GET <sfm_url>/health and show the result."""
|
|
import urllib.request
|
|
import urllib.error
|
|
|
|
self._sfm_test_status.config(text="Testing...", foreground="grey")
|
|
self._sfm_test_btn.config(state="disabled")
|
|
self.root.update_idletasks()
|
|
|
|
raw = self.var_sfm_url.get().strip()
|
|
if not raw:
|
|
self._sfm_test_status.config(text="Enter a URL first", foreground="orange")
|
|
self._sfm_test_btn.config(state="normal")
|
|
return
|
|
|
|
url = raw.rstrip("/") + "/health"
|
|
|
|
try:
|
|
req = urllib.request.Request(url)
|
|
with urllib.request.urlopen(req, timeout=5) as resp:
|
|
if resp.status == 200:
|
|
self._sfm_test_status.config(text="Connected!", foreground="green")
|
|
else:
|
|
self._sfm_test_status.config(
|
|
text="HTTP {}".format(resp.status), foreground="orange",
|
|
)
|
|
except urllib.error.URLError as e:
|
|
reason = str(e.reason) if hasattr(e, "reason") else str(e)
|
|
self._sfm_test_status.config(
|
|
text="Failed: {}".format(reason[:30]), foreground="red",
|
|
)
|
|
except Exception as e:
|
|
self._sfm_test_status.config(
|
|
text="Error: {}".format(str(e)[:30]), foreground="red",
|
|
)
|
|
finally:
|
|
self._sfm_test_btn.config(state="normal")
|
|
|
|
|
|
# --- Validation helpers ---
|
|
|
|
def _get_int_var(self, var, name, min_val, max_val, default):
|
|
"""Parse a StringVar as int, clamp to range, return clamped value or None on error."""
|
|
raw = var.get().strip()
|
|
try:
|
|
val = int(raw)
|
|
except ValueError:
|
|
messagebox.showerror(
|
|
"Validation Error",
|
|
"{} must be an integer (got: {!r}).".format(name, raw),
|
|
)
|
|
return None
|
|
if val < min_val or val > max_val:
|
|
messagebox.showerror(
|
|
"Validation Error",
|
|
"{} must be between {} and {} (got {}).".format(name, min_val, max_val, val),
|
|
)
|
|
return None
|
|
return val
|
|
|
|
# --- Save / Cancel ---
|
|
|
|
def _on_save(self):
|
|
# Validate numeric fields before writing
|
|
checks = [
|
|
(self.var_api_interval, "API Interval", 30, 3600, 300),
|
|
(self.var_max_event_age_days, "Max Event Age Days", 1, 3650, 365),
|
|
(self.var_scan_interval, "Scan Interval", 10, 3600, 300),
|
|
(self.var_mlg_header_bytes, "MLG Header Bytes", 256, 65536, 2048),
|
|
(self.var_log_retention_days, "Log Retention Days", 1, 365, 30),
|
|
(self.var_sfm_forward_interval, "SFM Forward Interval", 5, 3600, 60),
|
|
(self.var_sfm_quiescence, "SFM Quiescence", 1, 60, 5),
|
|
(self.var_sfm_missing_report_grace, "SFM Missing-Report Grace", 0, 600, 60),
|
|
(self.var_sfm_http_timeout, "SFM HTTP Timeout", 5, 600, 60),
|
|
]
|
|
int_values = {}
|
|
for var, name, mn, mx, dflt in checks:
|
|
result = self._get_int_var(var, name, mn, mx, dflt)
|
|
if result is None:
|
|
return # validation failed; keep dialog open
|
|
int_values[name] = result
|
|
|
|
# SFM forwarding requires a URL when enabled — common foot-gun
|
|
# to flip the checkbox without filling in the field.
|
|
if self.var_sfm_enabled.get() and not self.var_sfm_url.get().strip():
|
|
messagebox.showerror(
|
|
"Validation Error",
|
|
"SFM Forward is enabled but the SFM Server URL field is empty.\n\n"
|
|
"Either set the URL (e.g. http://10.0.0.44:8200) or uncheck "
|
|
"'Forward events to SFM'.",
|
|
)
|
|
return
|
|
|
|
# Resolve source_id placeholder
|
|
source_id = self.var_source_id.get().strip()
|
|
# Strip placeholder hint if user left it
|
|
if source_id.startswith("Defaults to hostname"):
|
|
source_id = ""
|
|
|
|
# Resolve api_url — append the fixed endpoint, strip placeholder
|
|
api_url = self.var_api_url.get().strip()
|
|
if api_url == "http://192.168.x.x:8000" or not api_url:
|
|
api_url = ""
|
|
else:
|
|
api_url = api_url.rstrip("/") + "/api/series3/heartbeat"
|
|
|
|
values = {
|
|
"API_ENABLED": "true" if self.var_api_enabled.get() else "false",
|
|
"API_URL": api_url,
|
|
"API_INTERVAL_SECONDS": str(int_values["API Interval"]),
|
|
"SOURCE_ID": source_id,
|
|
"SOURCE_TYPE": self.var_source_type.get().strip() or "series3_watcher",
|
|
"SERIES3_PATH": self.var_series3_path.get().strip(),
|
|
"MAX_EVENT_AGE_DAYS": str(int_values["Max Event Age Days"]),
|
|
"SCAN_INTERVAL_SECONDS":str(int_values["Scan Interval"]),
|
|
"MLG_HEADER_BYTES": str(int_values["MLG Header Bytes"]),
|
|
"ENABLE_LOGGING": "true" if self.var_enable_logging.get() else "false",
|
|
"LOG_FILE": self.var_log_file.get().strip(),
|
|
"LOG_RETENTION_DAYS": str(int_values["Log Retention Days"]),
|
|
"UPDATE_SOURCE": self.var_update_source.get().strip() or "gitea",
|
|
"UPDATE_URL": self.var_update_url.get().strip(),
|
|
|
|
# SFM event forwarder
|
|
"SFM_FORWARD_ENABLED": "true" if self.var_sfm_enabled.get() else "false",
|
|
"SFM_URL": self.var_sfm_url.get().strip().rstrip("/"),
|
|
"SFM_FORWARD_INTERVAL_SECONDS": str(int_values["SFM Forward Interval"]),
|
|
"SFM_QUIESCENCE_SECONDS": str(int_values["SFM Quiescence"]),
|
|
"SFM_MISSING_REPORT_GRACE_SECONDS": str(int_values["SFM Missing-Report Grace"]),
|
|
"SFM_HTTP_TIMEOUT": str(int_values["SFM HTTP Timeout"]),
|
|
"SFM_STATE_FILE": self.var_sfm_state_file.get().strip(),
|
|
}
|
|
|
|
try:
|
|
_save_config(self.config_path, values)
|
|
except Exception as e:
|
|
messagebox.showerror("Save Error", "Could not write config.ini:\n{}".format(e))
|
|
return
|
|
|
|
self.saved = True
|
|
self.root.destroy()
|
|
|
|
def _on_cancel(self):
|
|
self.saved = False
|
|
self.root.destroy()
|
|
|
|
|
|
# --------------- Public API ---------------
|
|
|
|
def show_dialog(config_path, wizard=False):
|
|
"""
|
|
Open the settings dialog.
|
|
|
|
Parameters
|
|
----------
|
|
config_path : str
|
|
Absolute path to config.ini (read if it exists, written on Save).
|
|
wizard : bool
|
|
If True, shows first-run welcome message and "Save & Start" button.
|
|
|
|
Returns
|
|
-------
|
|
bool
|
|
True if the user saved, False if they cancelled.
|
|
"""
|
|
root = tk.Tk()
|
|
root.withdraw() # hide blank root window
|
|
|
|
# Create a Toplevel that acts as the dialog window
|
|
top = tk.Toplevel(root)
|
|
top.deiconify()
|
|
|
|
dlg = SettingsDialog(top, config_path, wizard=wizard)
|
|
|
|
# Center after build
|
|
top.update_idletasks()
|
|
w = top.winfo_reqwidth()
|
|
h = top.winfo_reqheight()
|
|
sw = top.winfo_screenwidth()
|
|
sh = top.winfo_screenheight()
|
|
x = (sw - w) // 2
|
|
y = (sh - h) // 2
|
|
top.geometry("{}x{}+{}+{}".format(w, h, x, y))
|
|
|
|
root.wait_window(top)
|
|
root.destroy()
|
|
|
|
return dlg.saved
|