Files
terminal-web-server/front-generator/render.py

150 lines
4.3 KiB
Python

import json
from jinja2 import Environment, FileSystemLoader
import sys
import os
CONFIG_DIR = "config"
MODEM_TYPES = {}
for _fname in os.listdir(CONFIG_DIR):
if not _fname.endswith(".json"):
continue
path = os.path.join(CONFIG_DIR, _fname)
try:
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
except Exception as e:
print(f"[WARN] Failed to read {path}: {e}")
continue
modem_type = data.get("modem_type")
if modem_type is None:
print(f"[WARN] {_fname} ignored: no 'modem_type' field")
continue
MODEM_TYPES[modem_type] = data
def extract_param_names(mc):
result = []
def helper_extract(widget):
if 'childs' in widget:
r = []
for child in widget['childs']:
r += helper_extract(child)
return r
elif 'name' in widget:
copy_fields = {"widget": widget['widget'], "name": widget['name']}
if 'min' in widget:
copy_fields['min'] = widget['min']
if 'max' in widget:
copy_fields['max'] = widget['max']
if 'step' in widget:
copy_fields['step'] = widget['step']
match widget['widget']:
case 'select': return [{"initValue": widget['values'][0]['value']} | copy_fields]
case 'checkbox': return [{"initValue": 'false'} | copy_fields]
case 'number': return [{"initValue": widget['min'] if widget['min'] else '0'} | copy_fields]
case 'number-int': return [{"initValue": "0"} | copy_fields]
case 'modulation-modcod': return [copy_fields | {"name": widget['name'] + "Modulation", "initValue": '"QPSK"'}]
case 'modulation-speed': return [copy_fields | {"name": widget['name'] + "Speed", "initValue": '"1/4"'}]
case 'watch': return []
return [{"initValue": 'null'} | copy_fields]
return []
for cat in mc['params']:
ws = []
for w in mc['params'][cat]:
ws += helper_extract(w)
# ws.sort(key=lambda k: k['name'])
result.append({
"group": cat,
"params": ws
})
return result
def add_submit_widgets(params):
def find_submit(w):
if w['widget'] == 'submit':
return True
if 'childs' in w:
for c in w['childs']:
if find_submit(c):
return True
return False
for group in params:
wid_found = False
for wid in params[group]:
if find_submit(wid):
wid_found = True
break
if wid_found:
continue
params[group].append({"widget": "submit"})
def extract_param_groups(mc):
return [k for k in mc['params']]
def build_modem_env(modem):
if modem not in MODEM_TYPES:
raise RuntimeError(f"Modem '{modem}' is not exist in config!")
mc = MODEM_TYPES[modem]
add_submit_widgets(mc['params'])
return {
"modem": modem,
"modem_name": mc['modem_name'],
"header_tabs": mc['tabs'],
"tab_names_array": [t['name'] for t in mc['tabs']],
"params": mc["params"],
"dangerousParamGroups": mc["dangerousParamGroups"] if 'dangerousParamGroups' in mc else {},
"paramGroups": extract_param_names(mc),
"paramGroupsList": extract_param_groups(mc),
}
def render_modem(modem):
loader = FileSystemLoader('template')
env = Environment(loader=loader, trim_blocks=True, lstrip_blocks=True)
template = env.get_template('main.html')
context = build_modem_env(modem)
with open(f"out/main-{modem}.html", "w") as f:
f.write(template.render(context))
def render_modem_preview(modem):
loader = FileSystemLoader('template')
env = Environment(loader=loader, trim_blocks=True, lstrip_blocks=True)
template = env.get_template('modem-preview.md')
context = build_modem_env(modem)
with open(f"out/{modem}.md", "w") as f:
f.write(template.render(context))
if __name__ == '__main__':
os.makedirs('out', exist_ok=True)
for mt in MODEM_TYPES:
print(f'Generating {mt} modem...')
render_modem(mt)
render_modem_preview(mt)
os.system(f'cp -u out/main-{mt}.html ../static')
os.system(f'cp -u out/{mt}.md ../preview')