Go-based FM stereo transmitter with RDS, Windows-first and cross-platform
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

2509 linhas
79KB

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1">
  6. <title>fm-rds-tx</title>
  7. <style>
  8. @import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;600;700&family=Archivo+Black&display=swap');
  9. :root {
  10. --bg: #0a0a0c;
  11. --bg-2: #0f1015;
  12. --surface: #111116;
  13. --surface2: #18181e;
  14. --surface3: #1f2028;
  15. --border: #2a2a35;
  16. --border-strong: #3a3a49;
  17. --text: #d4d4dc;
  18. --text-dim: #8b8b99;
  19. --text-muted: #666674;
  20. --accent: #ff3b30;
  21. --accent-glow: #ff3b3044;
  22. --green: #30d158;
  23. --green-glow: #30d15844;
  24. --amber: #ff9f0a;
  25. --amber-glow: #ff9f0a44;
  26. --blue: #0a84ff;
  27. --blue-glow: #0a84ff33;
  28. --mono: 'JetBrains Mono', monospace;
  29. --display: 'Archivo Black', sans-serif;
  30. --radius: 8px;
  31. --shadow: 0 10px 30px rgba(0,0,0,.25);
  32. }
  33. * { box-sizing: border-box; margin: 0; padding: 0; }
  34. html { color-scheme: dark; }
  35. body {
  36. background:
  37. radial-gradient(circle at top right, rgba(10,132,255,.06), transparent 28%),
  38. radial-gradient(circle at top left, rgba(255,59,48,.06), transparent 30%),
  39. var(--bg);
  40. color: var(--text);
  41. font-family: var(--mono);
  42. font-size: 13px;
  43. line-height: 1.5;
  44. min-height: 100vh;
  45. overflow-x: hidden;
  46. }
  47. body::before {
  48. content: '';
  49. position: fixed; inset: 0;
  50. background: repeating-linear-gradient(0deg, transparent, transparent 2px, rgba(255,255,255,0.015) 2px, rgba(255,255,255,0.015) 4px);
  51. pointer-events: none;
  52. z-index: 1000;
  53. }
  54. button, input { font: inherit; }
  55. button { user-select: none; }
  56. .app {
  57. max-width: 1120px;
  58. margin: 0 auto;
  59. padding: 18px;
  60. }
  61. .header {
  62. display: flex;
  63. align-items: flex-start;
  64. justify-content: space-between;
  65. gap: 18px;
  66. padding: 8px 0 22px;
  67. border-bottom: 1px solid var(--border);
  68. margin-bottom: 18px;
  69. }
  70. .header-main {
  71. display: flex;
  72. flex-direction: column;
  73. gap: 8px;
  74. }
  75. .header h1 {
  76. font-family: var(--display);
  77. font-size: 24px;
  78. letter-spacing: 2px;
  79. text-transform: uppercase;
  80. color: var(--accent);
  81. text-shadow: 0 0 20px var(--accent-glow), 0 0 40px var(--accent-glow);
  82. }
  83. .header-sub {
  84. display: flex;
  85. flex-wrap: wrap;
  86. gap: 8px;
  87. }
  88. .badge {
  89. display: inline-flex;
  90. align-items: center;
  91. gap: 8px;
  92. min-height: 28px;
  93. padding: 0 10px;
  94. border: 1px solid var(--border);
  95. border-radius: 999px;
  96. background: rgba(255,255,255,0.02);
  97. color: var(--text-dim);
  98. font-size: 11px;
  99. text-transform: uppercase;
  100. letter-spacing: .8px;
  101. }
  102. .badge strong {
  103. color: var(--text);
  104. font-weight: 700;
  105. }
  106. .header-status {
  107. display: flex;
  108. align-items: center;
  109. gap: 10px;
  110. padding-top: 6px;
  111. }
  112. .led {
  113. width: 10px;
  114. height: 10px;
  115. border-radius: 50%;
  116. background: #333;
  117. box-shadow: none;
  118. transition: all .25s ease;
  119. flex-shrink: 0;
  120. }
  121. .led.on-green {
  122. background: var(--green);
  123. box-shadow: 0 0 8px var(--green), 0 0 20px var(--green-glow);
  124. }
  125. .led.on-red {
  126. background: var(--accent);
  127. box-shadow: 0 0 8px var(--accent), 0 0 20px var(--accent-glow);
  128. }
  129. .led.on-amber {
  130. background: var(--amber);
  131. box-shadow: 0 0 8px var(--amber), 0 0 20px var(--amber-glow);
  132. }
  133. .led.on-blue {
  134. background: var(--blue);
  135. box-shadow: 0 0 8px var(--blue), 0 0 20px var(--blue-glow);
  136. }
  137. .status-text {
  138. font-size: 10px;
  139. color: var(--text-dim);
  140. text-transform: uppercase;
  141. letter-spacing: 1.2px;
  142. }
  143. .layout {
  144. display: grid;
  145. grid-template-columns: minmax(0, 1.35fr) minmax(310px, .75fr);
  146. gap: 14px;
  147. align-items: start;
  148. }
  149. .stack { display: flex; flex-direction: column; gap: 12px; }
  150. .card {
  151. background: linear-gradient(180deg, rgba(255,255,255,0.02), rgba(255,255,255,0.01));
  152. border: 1px solid var(--border);
  153. border-radius: var(--radius);
  154. box-shadow: var(--shadow);
  155. }
  156. .hero {
  157. padding: 16px;
  158. position: relative;
  159. overflow: hidden;
  160. }
  161. .hero.tx-live::after {
  162. content: '';
  163. position: absolute;
  164. inset: -40%;
  165. background: radial-gradient(circle, rgba(48,209,88,.12), transparent 55%);
  166. animation: pulseGlow 2.8s ease-in-out infinite;
  167. pointer-events: none;
  168. }
  169. .hero.tx-busy::after {
  170. content: '';
  171. position: absolute;
  172. inset: -50%;
  173. background: conic-gradient(from 0deg, transparent, rgba(255,159,10,.12), transparent 45%);
  174. animation: spinWash 2s linear infinite;
  175. pointer-events: none;
  176. }
  177. @keyframes pulseGlow {
  178. 0%, 100% { transform: scale(.95); opacity: .45; }
  179. 50% { transform: scale(1.05); opacity: .8; }
  180. }
  181. @keyframes spinWash {
  182. from { transform: rotate(0deg); }
  183. to { transform: rotate(360deg); }
  184. }
  185. @keyframes blinkSoft {
  186. 0%, 100% { opacity: 1; }
  187. 50% { opacity: .55; }
  188. }
  189. .tx-bar {
  190. position: relative;
  191. z-index: 1;
  192. display: grid;
  193. grid-template-columns: minmax(180px, 250px) 1fr auto;
  194. gap: 14px;
  195. align-items: center;
  196. }
  197. .freq-display-wrap {
  198. display: flex;
  199. flex-direction: column;
  200. gap: 6px;
  201. }
  202. .freq-display-label {
  203. font-size: 10px;
  204. text-transform: uppercase;
  205. letter-spacing: 1.4px;
  206. color: var(--text-dim);
  207. }
  208. .freq-display {
  209. font-family: var(--display);
  210. font-size: 38px;
  211. color: var(--green);
  212. text-shadow: 0 0 15px var(--green-glow);
  213. letter-spacing: 1px;
  214. line-height: 1;
  215. }
  216. .freq-display .unit {
  217. font-family: var(--mono);
  218. font-size: 14px;
  219. color: var(--text-dim);
  220. margin-left: 5px;
  221. }
  222. .tx-actions {
  223. display: flex;
  224. flex-wrap: wrap;
  225. gap: 10px;
  226. }
  227. .tx-btn, .ghost-btn, .apply-btn, .preset-btn, .danger-btn {
  228. min-height: 40px;
  229. padding: 0 18px;
  230. border-radius: var(--radius);
  231. border: 1px solid var(--border);
  232. background: var(--surface2);
  233. color: var(--text);
  234. cursor: pointer;
  235. font-size: 12px;
  236. font-weight: 700;
  237. text-transform: uppercase;
  238. letter-spacing: 1px;
  239. transition: all .16s ease;
  240. }
  241. .tx-btn:hover, .ghost-btn:hover, .apply-btn:hover, .preset-btn:hover, .danger-btn:hover {
  242. transform: translateY(-1px);
  243. border-color: var(--border-strong);
  244. }
  245. .tx-btn:disabled, .ghost-btn:disabled, .apply-btn:disabled, .preset-btn:disabled, .danger-btn:disabled {
  246. opacity: .45;
  247. cursor: not-allowed;
  248. transform: none;
  249. }
  250. .tx-btn.start { border-color: var(--green); color: var(--green); }
  251. .tx-btn.start:hover:not(:disabled) { background: rgba(48,209,88,.1); }
  252. .tx-btn.stop { border-color: var(--accent); color: var(--accent); }
  253. .tx-btn.stop:hover:not(:disabled) { background: rgba(255,59,48,.1); }
  254. .ghost-btn { color: var(--text-dim); }
  255. .danger-btn {
  256. border-color: rgba(255,59,48,.45);
  257. color: var(--accent);
  258. background: rgba(255,59,48,.04);
  259. }
  260. .danger-btn:hover:not(:disabled) {
  261. background: rgba(255,59,48,.12);
  262. }
  263. .tx-state-wrap {
  264. display: flex;
  265. flex-direction: column;
  266. align-items: flex-end;
  267. gap: 6px;
  268. }
  269. .tx-state {
  270. font-size: 11px;
  271. text-transform: uppercase;
  272. letter-spacing: 2px;
  273. color: var(--text-dim);
  274. }
  275. .tx-state.running { color: var(--green); animation: blinkSoft 2s ease-in-out infinite; }
  276. .tx-state.idle, .tx-state.stopped { color: var(--text-dim); }
  277. .tx-state.starting, .tx-state.stopping, .tx-state.working { color: var(--amber); animation: blinkSoft 1.1s ease-in-out infinite; }
  278. .tx-state.error { color: var(--accent); }
  279. .status-hint {
  280. font-size: 10px;
  281. color: var(--text-muted);
  282. text-align: right;
  283. }
  284. .quick-grid {
  285. position: relative;
  286. z-index: 1;
  287. display: grid;
  288. grid-template-columns: repeat(5, minmax(0, 1fr));
  289. gap: 10px;
  290. margin-top: 16px;
  291. }
  292. .quick-item {
  293. padding: 12px;
  294. border: 1px solid var(--border);
  295. border-radius: var(--radius);
  296. background: var(--bg-2);
  297. }
  298. .quick-item .label {
  299. font-size: 9px;
  300. text-transform: uppercase;
  301. letter-spacing: 1.4px;
  302. color: var(--text-dim);
  303. margin-bottom: 6px;
  304. }
  305. .quick-item .value {
  306. font-size: 18px;
  307. font-weight: 700;
  308. color: var(--text);
  309. }
  310. .quick-item .value.warn { color: var(--amber); }
  311. .quick-item .value.err { color: var(--accent); }
  312. .quick-item .value.good { color: var(--green); }
  313. .signal-grid {
  314. position: relative;
  315. z-index: 1;
  316. display: grid;
  317. grid-template-columns: repeat(3, minmax(0, 1fr));
  318. gap: 10px;
  319. margin-top: 12px;
  320. }
  321. .signal-card {
  322. padding: 12px;
  323. border: 1px solid var(--border);
  324. border-radius: var(--radius);
  325. background: var(--bg-2);
  326. }
  327. .signal-head {
  328. display: flex;
  329. align-items: center;
  330. justify-content: space-between;
  331. gap: 10px;
  332. margin-bottom: 8px;
  333. }
  334. .signal-title {
  335. font-size: 10px;
  336. color: var(--text-dim);
  337. text-transform: uppercase;
  338. letter-spacing: 1.2px;
  339. }
  340. .signal-value {
  341. font-size: 11px;
  342. color: var(--text);
  343. font-weight: 700;
  344. }
  345. .meter {
  346. width: 100%;
  347. height: 10px;
  348. border-radius: 999px;
  349. background: #171821;
  350. border: 1px solid var(--border);
  351. overflow: hidden;
  352. }
  353. .meter-fill {
  354. height: 100%;
  355. width: 0%;
  356. transition: width .25s ease, background-color .25s ease;
  357. background: linear-gradient(90deg, var(--green), #5cff90);
  358. }
  359. .meter-fill.warn {
  360. background: linear-gradient(90deg, var(--amber), #ffc45b);
  361. }
  362. .meter-fill.err {
  363. background: linear-gradient(90deg, var(--accent), #ff6b63);
  364. }
  365. .spark {
  366. width: 100%;
  367. height: 34px;
  368. margin-top: 10px;
  369. border-radius: 6px;
  370. background: rgba(255,255,255,0.01);
  371. border: 1px solid rgba(255,255,255,0.03);
  372. }
  373. .spark path.line {
  374. fill: none;
  375. stroke-width: 2;
  376. stroke-linecap: round;
  377. stroke-linejoin: round;
  378. }
  379. .spark path.area {
  380. opacity: .14;
  381. }
  382. .spark.good path.line { stroke: var(--green); }
  383. .spark.good path.area { fill: var(--green); }
  384. .spark.warn path.line { stroke: var(--amber); }
  385. .spark.warn path.area { fill: var(--amber); }
  386. .spark.err path.line { stroke: var(--accent); }
  387. .spark.err path.area { fill: var(--accent); }
  388. .panel {
  389. overflow: hidden;
  390. }
  391. .panel-head {
  392. display: flex;
  393. align-items: center;
  394. gap: 8px;
  395. padding: 12px 14px;
  396. border-bottom: 1px solid var(--border);
  397. background: var(--surface2);
  398. cursor: pointer;
  399. user-select: none;
  400. }
  401. .panel-head h2 {
  402. font-size: 11px;
  403. font-weight: 700;
  404. text-transform: uppercase;
  405. letter-spacing: 1.6px;
  406. color: var(--text-dim);
  407. }
  408. .panel-head .meta {
  409. margin-left: auto;
  410. margin-right: 8px;
  411. font-size: 10px;
  412. color: var(--text-muted);
  413. text-transform: uppercase;
  414. letter-spacing: 1px;
  415. }
  416. .panel-head .chevron {
  417. color: var(--text-dim);
  418. transition: transform .2s ease;
  419. font-size: 10px;
  420. }
  421. .panel-head.collapsed .chevron { transform: rotate(-90deg); }
  422. .panel-body { padding: 14px; }
  423. .panel-body.collapsed { display: none; }
  424. .section-note {
  425. font-size: 11px;
  426. color: var(--text-muted);
  427. margin-bottom: 12px;
  428. }
  429. .shortcuts-grid {
  430. display: grid;
  431. grid-template-columns: repeat(2, minmax(0, 1fr));
  432. gap: 8px 12px;
  433. }
  434. .shortcut-line {
  435. display: flex;
  436. align-items: center;
  437. justify-content: space-between;
  438. gap: 12px;
  439. padding: 7px 0;
  440. border-bottom: 1px solid #1a1a22;
  441. }
  442. .shortcut-line:last-child { border-bottom: none; }
  443. .shortcut-line .name { font-size: 11px; color: var(--text-dim); }
  444. .shortcut-line .keys {
  445. display: inline-flex;
  446. gap: 6px;
  447. flex-wrap: wrap;
  448. }
  449. .kbd {
  450. min-width: 28px;
  451. padding: 3px 7px;
  452. border: 1px solid var(--border);
  453. border-bottom-width: 2px;
  454. border-radius: 6px;
  455. background: var(--bg-2);
  456. font-size: 10px;
  457. color: var(--text);
  458. text-align: center;
  459. }
  460. .preset-row {
  461. display: flex;
  462. flex-wrap: wrap;
  463. gap: 8px;
  464. margin-bottom: 12px;
  465. }
  466. .preset-btn {
  467. min-height: 34px;
  468. padding: 0 12px;
  469. font-size: 11px;
  470. letter-spacing: .8px;
  471. color: var(--text-dim);
  472. }
  473. .preset-btn.active {
  474. border-color: var(--blue);
  475. color: var(--blue);
  476. background: rgba(10,132,255,.08);
  477. }
  478. .preset-btn.rds {
  479. text-transform: none;
  480. font-weight: 600;
  481. }
  482. .ctrl-row {
  483. display: flex;
  484. align-items: center;
  485. gap: 12px;
  486. padding: 10px 0;
  487. border-bottom: 1px solid #1a1a22;
  488. }
  489. .ctrl-row:last-child { border-bottom: none; }
  490. .ctrl-label-wrap {
  491. min-width: 130px;
  492. display: flex;
  493. flex-direction: column;
  494. gap: 2px;
  495. }
  496. .ctrl-label {
  497. font-size: 11px;
  498. color: var(--text-dim);
  499. text-transform: uppercase;
  500. letter-spacing: .8px;
  501. }
  502. .ctrl-sub {
  503. font-size: 10px;
  504. color: var(--text-muted);
  505. }
  506. .ctrl-input {
  507. flex: 1;
  508. display: flex;
  509. align-items: center;
  510. gap: 10px;
  511. }
  512. input[type="range"] {
  513. -webkit-appearance: none;
  514. appearance: none;
  515. flex: 1;
  516. height: 6px;
  517. background: linear-gradient(90deg, var(--border), var(--surface3));
  518. border-radius: 999px;
  519. outline: none;
  520. }
  521. input[type="range"]::-webkit-slider-thumb {
  522. -webkit-appearance: none;
  523. width: 16px;
  524. height: 16px;
  525. border-radius: 50%;
  526. background: var(--text);
  527. border: 2px solid var(--bg);
  528. cursor: pointer;
  529. transition: background .15s ease, transform .15s ease;
  530. }
  531. input[type="range"]::-webkit-slider-thumb:hover {
  532. background: var(--accent);
  533. transform: scale(1.06);
  534. }
  535. input[type="number"], input[type="text"] {
  536. background: var(--bg);
  537. border: 1px solid var(--border);
  538. border-radius: 6px;
  539. color: var(--text);
  540. padding: 8px 10px;
  541. outline: none;
  542. transition: border-color .15s ease, box-shadow .15s ease, background-color .15s ease;
  543. }
  544. input[type="number"] {
  545. width: 92px;
  546. text-align: right;
  547. }
  548. input[type="text"] { width: 100%; }
  549. input:focus {
  550. border-color: var(--accent);
  551. box-shadow: 0 0 0 3px rgba(255,59,48,.12);
  552. }
  553. input.input-dirty {
  554. border-color: var(--amber);
  555. box-shadow: 0 0 0 3px rgba(255,159,10,.08);
  556. }
  557. input.input-error {
  558. border-color: var(--accent);
  559. box-shadow: 0 0 0 3px rgba(255,59,48,.14);
  560. background: rgba(255,59,48,.04);
  561. }
  562. .val-display {
  563. min-width: 64px;
  564. text-align: right;
  565. font-size: 12px;
  566. font-weight: 700;
  567. color: var(--text);
  568. }
  569. .unit-label {
  570. font-size: 11px;
  571. color: var(--text-dim);
  572. min-width: 44px;
  573. }
  574. .field-error {
  575. display: none;
  576. margin-top: 8px;
  577. font-size: 11px;
  578. color: var(--accent);
  579. }
  580. .field-error.show { display: block; }
  581. .toggle-row {
  582. display: flex;
  583. align-items: center;
  584. justify-content: space-between;
  585. gap: 14px;
  586. padding: 12px 0;
  587. border-bottom: 1px solid #1a1a22;
  588. }
  589. .toggle-row:last-child { border-bottom: none; }
  590. .toggle-copy {
  591. display: flex;
  592. flex-direction: column;
  593. gap: 3px;
  594. }
  595. .toggle-copy .title {
  596. font-size: 12px;
  597. color: var(--text);
  598. font-weight: 700;
  599. }
  600. .toggle-copy .sub {
  601. font-size: 10px;
  602. color: var(--text-muted);
  603. }
  604. .toggle-ctl {
  605. display: flex;
  606. align-items: center;
  607. gap: 10px;
  608. }
  609. .toggle {
  610. position: relative;
  611. width: 42px;
  612. height: 24px;
  613. background: var(--border);
  614. border-radius: 999px;
  615. cursor: pointer;
  616. transition: all .2s ease;
  617. flex-shrink: 0;
  618. }
  619. .toggle::after {
  620. content: '';
  621. position: absolute;
  622. top: 3px;
  623. left: 3px;
  624. width: 18px;
  625. height: 18px;
  626. background: var(--text);
  627. border-radius: 50%;
  628. transition: transform .2s ease;
  629. }
  630. .toggle.on { background: var(--green); }
  631. .toggle.on::after { transform: translateX(18px); }
  632. .toggle.busy { opacity: .55; pointer-events: none; }
  633. .toggle-state {
  634. min-width: 52px;
  635. text-align: right;
  636. font-size: 11px;
  637. color: var(--text-dim);
  638. text-transform: uppercase;
  639. letter-spacing: 1px;
  640. }
  641. .rds-grid {
  642. display: grid;
  643. gap: 12px;
  644. }
  645. .rds-field {
  646. display: flex;
  647. flex-direction: column;
  648. gap: 6px;
  649. }
  650. .rds-input {
  651. width: 100%;
  652. background: var(--bg);
  653. border: 1px solid var(--border);
  654. border-radius: 6px;
  655. color: var(--green);
  656. font-family: var(--mono);
  657. font-size: 15px;
  658. font-weight: 700;
  659. padding: 10px 12px;
  660. outline: none;
  661. letter-spacing: 2px;
  662. text-transform: uppercase;
  663. }
  664. .rds-input.rt {
  665. color: var(--text);
  666. text-transform: none;
  667. letter-spacing: .5px;
  668. font-size: 12px;
  669. font-weight: 500;
  670. }
  671. .rds-charcount {
  672. font-size: 10px;
  673. color: var(--text-dim);
  674. text-align: right;
  675. }
  676. .actions-row {
  677. display: flex;
  678. gap: 10px;
  679. flex-wrap: wrap;
  680. margin-top: 14px;
  681. }
  682. .apply-btn {
  683. background: var(--accent);
  684. border-color: transparent;
  685. color: #fff;
  686. }
  687. .apply-btn.secondary {
  688. background: var(--surface2);
  689. color: var(--text-dim);
  690. border-color: var(--border);
  691. }
  692. .apply-btn.ok { background: var(--green); color: var(--bg); }
  693. .sidebar-card {
  694. padding: 14px;
  695. }
  696. .sidebar-section + .sidebar-section {
  697. margin-top: 14px;
  698. padding-top: 14px;
  699. border-top: 1px solid var(--border);
  700. }
  701. .sidebar-title {
  702. font-size: 11px;
  703. text-transform: uppercase;
  704. letter-spacing: 1.4px;
  705. color: var(--text-dim);
  706. margin-bottom: 10px;
  707. }
  708. .kv {
  709. display: grid;
  710. grid-template-columns: auto 1fr;
  711. gap: 8px 12px;
  712. align-items: start;
  713. }
  714. .kv .k {
  715. font-size: 10px;
  716. color: var(--text-muted);
  717. text-transform: uppercase;
  718. letter-spacing: 1px;
  719. }
  720. .kv .v {
  721. font-size: 12px;
  722. color: var(--text);
  723. word-break: break-word;
  724. }
  725. .health-line {
  726. display: flex;
  727. align-items: center;
  728. justify-content: space-between;
  729. gap: 10px;
  730. padding: 8px 0;
  731. border-bottom: 1px solid #1a1a22;
  732. }
  733. .health-line:last-child { border-bottom: none; }
  734. .health-line .name {
  735. font-size: 11px;
  736. color: var(--text-dim);
  737. }
  738. .health-line .val {
  739. font-size: 11px;
  740. color: var(--text);
  741. text-align: right;
  742. }
  743. .health-line .val.good { color: var(--green); }
  744. .health-line .val.warn { color: var(--amber); }
  745. .health-line .val.err { color: var(--accent); }
  746. .health-trend {
  747. margin-top: 10px;
  748. }
  749. .health-trend-label {
  750. font-size: 10px;
  751. text-transform: uppercase;
  752. letter-spacing: 1px;
  753. color: var(--text-muted);
  754. margin-bottom: 6px;
  755. }
  756. .fault-history {
  757. margin-top: 12px;
  758. padding: 10px;
  759. border: 1px solid var(--border);
  760. border-radius: 6px;
  761. background: var(--surface1);
  762. font-size: 11px;
  763. max-height: 180px;
  764. overflow-y: auto;
  765. line-height: 1.3;
  766. }
  767. .fault-history-entry {
  768. display: flex;
  769. justify-content: space-between;
  770. gap: 10px;
  771. padding: 4px 0;
  772. border-bottom: 1px solid rgba(255, 255, 255, 0.08);
  773. }
  774. .fault-history-entry:last-child {
  775. border-bottom: none;
  776. }
  777. .fault-history-entry .fault-history-time {
  778. color: var(--text-dim);
  779. }
  780. .fault-history-entry.ok { color: var(--green); }
  781. .fault-history-entry.warn { color: var(--amber); }
  782. .fault-history-entry.err { color: var(--accent); }
  783. .fault-history-desc {
  784. font-size: 10px;
  785. flex: 1;
  786. text-transform: uppercase;
  787. letter-spacing: 0.5px;
  788. }
  789. .fault-history-empty {
  790. padding: 6px 0;
  791. color: var(--text-muted);
  792. font-size: 11px;
  793. }
  794. .transition-history {
  795. margin-top: 12px;
  796. padding: 10px;
  797. border: 1px solid var(--border);
  798. border-radius: 6px;
  799. background: var(--surface);
  800. font-size: 11px;
  801. max-height: 180px;
  802. overflow-y: auto;
  803. line-height: 1.3;
  804. }
  805. .transition-history-entry {
  806. display: flex;
  807. justify-content: space-between;
  808. gap: 10px;
  809. padding: 4px 0;
  810. border-bottom: 1px solid rgba(255, 255, 255, 0.08);
  811. }
  812. .transition-history-entry:last-child {
  813. border-bottom: none;
  814. }
  815. .transition-history-entry .transition-history-time {
  816. color: var(--text-dim);
  817. }
  818. .transition-history-entry.good { color: var(--green); }
  819. .transition-history-entry.warn { color: var(--amber); }
  820. .transition-history-entry.err { color: var(--accent); }
  821. .transition-history-entry.info { color: var(--text); }
  822. .transition-history-desc {
  823. font-size: 10px;
  824. flex: 1;
  825. text-transform: uppercase;
  826. letter-spacing: 0.5px;
  827. }
  828. .transition-history-empty {
  829. padding: 6px 0;
  830. color: var(--text-muted);
  831. font-size: 11px;
  832. }
  833. .section-note.reset-hint {
  834. font-size: 11px;
  835. color: var(--text-dim);
  836. margin-top: 10px;
  837. }
  838. .log {
  839. background: var(--bg);
  840. border: 1px solid var(--border);
  841. border-radius: 6px;
  842. padding: 10px;
  843. font-size: 10px;
  844. color: var(--text-dim);
  845. max-height: 220px;
  846. overflow-y: auto;
  847. white-space: pre-wrap;
  848. word-break: break-word;
  849. }
  850. .log .entry { padding: 3px 0; }
  851. .log .entry.err { color: var(--accent); }
  852. .log .entry.ok { color: var(--green); }
  853. .log .entry.warn { color: var(--amber); }
  854. .log .entry.info { color: var(--blue); }
  855. .empty-log {
  856. color: var(--text-muted);
  857. }
  858. .toast {
  859. position: fixed;
  860. right: 16px;
  861. bottom: 16px;
  862. max-width: min(420px, calc(100vw - 24px));
  863. padding: 12px 15px;
  864. border-radius: var(--radius);
  865. font-size: 12px;
  866. font-weight: 700;
  867. z-index: 2000;
  868. transform: translateY(60px);
  869. opacity: 0;
  870. transition: all .25s ease;
  871. box-shadow: var(--shadow);
  872. }
  873. .toast.show { transform: translateY(0); opacity: 1; }
  874. .toast.ok { background: var(--green); color: var(--bg); }
  875. .toast.err { background: var(--accent); color: #fff; }
  876. .toast.info { background: var(--blue); color: #fff; }
  877. .toast.warn { background: var(--amber); color: #141414; }
  878. @media (max-width: 980px) {
  879. .layout { grid-template-columns: 1fr; }
  880. .tx-bar {
  881. grid-template-columns: 1fr;
  882. align-items: stretch;
  883. }
  884. .tx-state-wrap {
  885. align-items: flex-start;
  886. }
  887. .status-hint { text-align: left; }
  888. .quick-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
  889. .signal-grid { grid-template-columns: 1fr; }
  890. }
  891. @media (max-width: 640px) {
  892. .app { padding: 12px; }
  893. .header { flex-direction: column; align-items: stretch; gap: 10px; }
  894. .header h1 { font-size: 22px; }
  895. .header-sub { gap: 6px; }
  896. .badge { width: 100%; justify-content: space-between; }
  897. .quick-grid { grid-template-columns: 1fr 1fr; gap: 8px; }
  898. .quick-item { padding: 10px; }
  899. .quick-item .value { font-size: 16px; }
  900. .ctrl-row { flex-direction: column; align-items: stretch; }
  901. .ctrl-label-wrap { min-width: auto; }
  902. .ctrl-input { flex-wrap: wrap; }
  903. input[type="number"] { width: 100%; text-align: left; }
  904. .actions-row, .tx-actions { flex-direction: column; }
  905. .tx-btn, .ghost-btn, .apply-btn, .preset-btn, .danger-btn { width: 100%; }
  906. .panel-head { padding: 11px 12px; }
  907. .panel-body, .sidebar-card { padding: 12px; }
  908. .freq-display { font-size: 31px; }
  909. .preset-row { flex-direction: column; }
  910. .shortcuts-grid { grid-template-columns: 1fr; }
  911. }
  912. </style>
  913. </head>
  914. <body>
  915. <div class="app">
  916. <div class="header">
  917. <div class="header-main">
  918. <h1>FM-RDS-TX</h1>
  919. <div class="header-sub">
  920. <div class="badge"><span>Backend</span><strong id="badge-backend">--</strong></div>
  921. <div class="badge"><span>Mode</span><strong id="badge-mode">Control Plane</strong></div>
  922. <div class="badge"><span>Live Config</span><strong id="badge-live">--</strong></div>
  923. </div>
  924. </div>
  925. <div class="header-status">
  926. <div class="led" id="led-conn"></div>
  927. <div class="status-text" id="conn-label">connecting</div>
  928. </div>
  929. </div>
  930. <div class="layout">
  931. <div class="stack">
  932. <div class="card hero" id="hero-card">
  933. <div class="tx-bar">
  934. <div class="freq-display-wrap">
  935. <div class="freq-display-label">Carrier</div>
  936. <div class="freq-display" id="freq-display">---.-<span class="unit">MHz</span></div>
  937. </div>
  938. <div class="tx-actions">
  939. <button class="tx-btn start" id="btn-start" type="button">TX ON</button>
  940. <button class="tx-btn stop" id="btn-stop" type="button">TX OFF</button>
  941. <button class="ghost-btn" id="btn-refresh" type="button">Refresh</button>
  942. </div>
  943. <div class="tx-state-wrap">
  944. <div class="tx-state idle" id="tx-state">IDLE</div>
  945. <div class="status-hint" id="tx-hint">Awaiting runtime data</div>
  946. </div>
  947. </div>
  948. <div class="quick-grid">
  949. <div class="quick-item">
  950. <div class="label">Chunks</div>
  951. <div class="value" id="t-chunks">--</div>
  952. </div>
  953. <div class="quick-item">
  954. <div class="label">Samples</div>
  955. <div class="value" id="t-samples">--</div>
  956. </div>
  957. <div class="quick-item">
  958. <div class="label">Underruns</div>
  959. <div class="value" id="t-underruns">--</div>
  960. </div>
  961. <div class="quick-item">
  962. <div class="label">Uptime</div>
  963. <div class="value" id="t-uptime">--</div>
  964. </div>
  965. <div class="quick-item">
  966. <div class="label">Rate</div>
  967. <div class="value" id="t-rate">--</div>
  968. </div>
  969. </div>
  970. <div class="signal-grid">
  971. <div class="signal-card">
  972. <div class="signal-head">
  973. <div class="signal-title">Audio Buffer</div>
  974. <div class="signal-value" id="meter-audio-text">--</div>
  975. </div>
  976. <div class="meter"><div class="meter-fill" id="meter-audio-fill"></div></div>
  977. <svg class="spark good" id="spark-audio" viewBox="0 0 160 34" preserveAspectRatio="none"></svg>
  978. </div>
  979. <div class="signal-card">
  980. <div class="signal-head">
  981. <div class="signal-title">Stream Health</div>
  982. <div class="signal-value" id="meter-stream-text">--</div>
  983. </div>
  984. <div class="meter"><div class="meter-fill" id="meter-stream-fill"></div></div>
  985. <svg class="spark warn" id="spark-underruns" viewBox="0 0 160 34" preserveAspectRatio="none"></svg>
  986. </div>
  987. <div class="signal-card">
  988. <div class="signal-head">
  989. <div class="signal-title">TX Activity</div>
  990. <div class="signal-value" id="meter-tx-text">--</div>
  991. </div>
  992. <div class="meter"><div class="meter-fill" id="meter-tx-fill"></div></div>
  993. <svg class="spark good" id="spark-tx" viewBox="0 0 160 34" preserveAspectRatio="none"></svg>
  994. </div>
  995. </div>
  996. </div>
  997. <div class="card panel" data-panel-key="frequency">
  998. <div class="panel-head" data-panel>
  999. <div class="led on-green" style="width:6px;height:6px"></div>
  1000. <h2>Frequency</h2>
  1001. <div class="meta" id="freq-meta">Live-tunable</div>
  1002. <span class="chevron">▼</span>
  1003. </div>
  1004. <div class="panel-body">
  1005. <div class="section-note">Tune the RF carrier without restarting the control plane. Draft values stay local until you apply them.</div>
  1006. <div class="preset-row" id="freq-presets">
  1007. <button class="preset-btn" type="button" data-freq-preset="87.6">87.6 MHz</button>
  1008. <button class="preset-btn" type="button" data-freq-preset="94.5">94.5 MHz</button>
  1009. <button class="preset-btn" type="button" data-freq-preset="99.5">99.5 MHz</button>
  1010. <button class="preset-btn" type="button" data-freq-preset="100.0">100.0 MHz</button>
  1011. <button class="preset-btn" type="button" data-freq-preset="107.9">107.9 MHz</button>
  1012. </div>
  1013. <div class="ctrl-row">
  1014. <div class="ctrl-label-wrap">
  1015. <span class="ctrl-label">TX Freq</span>
  1016. <span class="ctrl-sub">Valid range 65–110 MHz</span>
  1017. </div>
  1018. <div class="ctrl-input">
  1019. <input type="range" min="65" max="110" step="0.1" id="freq-slider">
  1020. <input type="number" min="65" max="110" step="0.1" id="freq-num">
  1021. <span class="unit-label">MHz</span>
  1022. </div>
  1023. </div>
  1024. <div class="field-error" id="freq-error"></div>
  1025. <div class="actions-row">
  1026. <button class="apply-btn" id="freq-apply" type="button">Apply Frequency</button>
  1027. <button class="apply-btn secondary" id="freq-reset" type="button">Reset</button>
  1028. </div>
  1029. </div>
  1030. </div>
  1031. <div class="card panel" data-panel-key="switches">
  1032. <div class="panel-head" data-panel>
  1033. <div class="led on-green" style="width:6px;height:6px"></div>
  1034. <h2>Switches</h2>
  1035. <div class="meta">Live</div>
  1036. <span class="chevron">▼</span>
  1037. </div>
  1038. <div class="panel-body">
  1039. <div class="section-note">These switches apply immediately and show a busy state while the request is in flight.</div>
  1040. <div class="toggle-row">
  1041. <div class="toggle-copy">
  1042. <div class="title">Stereo</div>
  1043. <div class="sub">19 kHz pilot + 38 kHz DSB-SC</div>
  1044. </div>
  1045. <div class="toggle-ctl">
  1046. <div class="toggle" id="tog-stereo" data-toggle="stereoEnabled" role="switch" aria-checked="false" tabindex="0"></div>
  1047. <div class="toggle-state" id="stereo-label">--</div>
  1048. </div>
  1049. </div>
  1050. <div class="toggle-row">
  1051. <div class="toggle-copy">
  1052. <div class="title">RDS</div>
  1053. <div class="sub">57 kHz subcarrier encoder</div>
  1054. </div>
  1055. <div class="toggle-ctl">
  1056. <div class="toggle" id="tog-rds" data-toggle="rdsEnabled" role="switch" aria-checked="false" tabindex="0"></div>
  1057. <div class="toggle-state" id="rds-label">--</div>
  1058. </div>
  1059. </div>
  1060. <div class="toggle-row">
  1061. <div class="toggle-copy">
  1062. <div class="title">Limiter</div>
  1063. <div class="sub">MPX peak protection</div>
  1064. </div>
  1065. <div class="toggle-ctl">
  1066. <div class="toggle" id="tog-limiter" data-toggle="limiterEnabled" role="switch" aria-checked="false" tabindex="0"></div>
  1067. <div class="toggle-state" id="limiter-label">--</div>
  1068. </div>
  1069. </div>
  1070. </div>
  1071. </div>
  1072. <div class="card panel" data-panel-key="rds">
  1073. <div class="panel-head" data-panel>
  1074. <div class="led on-amber" style="width:6px;height:6px"></div>
  1075. <h2>RDS Text</h2>
  1076. <div class="meta" id="rds-meta">PS + RT</div>
  1077. <span class="chevron">▼</span>
  1078. </div>
  1079. <div class="panel-body">
  1080. <div class="section-note">Edit Program Service and RadioText without losing in-progress typing when the page refreshes itself.</div>
  1081. <div class="preset-row" id="rds-presets">
  1082. <button class="preset-btn rds" type="button" data-rds-ps="FMRTX" data-rds-rt="fm-rds-tx live">Station ID</button>
  1083. <button class="preset-btn rds" type="button" data-rds-ps="ONAIR" data-rds-rt="Now broadcasting">On Air</button>
  1084. <button class="preset-btn rds" type="button" data-rds-ps="LIVE" data-rds-rt="Live set in progress">Live Set</button>
  1085. <button class="preset-btn rds" type="button" data-rds-ps="TEST" data-rds-rt="RDS test transmission">Test</button>
  1086. </div>
  1087. <div class="rds-grid">
  1088. <div class="rds-field">
  1089. <span class="ctrl-label">Program Service (PS)</span>
  1090. <input type="text" class="rds-input" id="rds-ps" maxlength="8" placeholder="STATION" spellcheck="false">
  1091. <div class="rds-charcount"><span id="ps-count">0</span>/8</div>
  1092. <div class="field-error" id="ps-error"></div>
  1093. </div>
  1094. <div class="rds-field">
  1095. <span class="ctrl-label">RadioText (RT)</span>
  1096. <input type="text" class="rds-input rt" id="rds-rt" maxlength="64" placeholder="Now playing..." spellcheck="false">
  1097. <div class="rds-charcount"><span id="rt-count">0</span>/64</div>
  1098. <div class="field-error" id="rt-error"></div>
  1099. </div>
  1100. </div>
  1101. <div class="actions-row">
  1102. <button class="apply-btn" id="rds-apply" type="button">Apply RDS Text</button>
  1103. <button class="apply-btn secondary" id="rds-reset" type="button">Reset</button>
  1104. </div>
  1105. </div>
  1106. </div>
  1107. </div>
  1108. <div class="stack">
  1109. <div class="card sidebar-card">
  1110. <div class="sidebar-section">
  1111. <div class="sidebar-title">System Snapshot</div>
  1112. <div class="kv">
  1113. <div class="k">Backend</div><div class="v" id="info-backend">--</div>
  1114. <div class="k">Frequency</div><div class="v" id="info-freq">--</div>
  1115. <div class="k">Pre-emphasis</div><div class="v" id="info-preemph">--</div>
  1116. <div class="k">FM Mod</div><div class="v" id="info-fmmod">--</div>
  1117. <div class="k">Live Config</div><div class="v" id="info-live">--</div>
  1118. </div>
  1119. </div>
  1120. <div class="sidebar-section">
  1121. <div class="sidebar-title">Health</div>
  1122. <div class="health-line"><div class="name">HTTP</div><div class="val" id="health-http">--</div></div>
  1123. <div class="health-line"><div class="name">Runtime</div><div class="val" id="health-runtime">--</div></div>
  1124. <div class="health-line"><div class="name">State Age</div><div class="val" id="health-state-age">--</div></div>
  1125. <div class="health-line"><div class="name">Runtime Signal</div><div class="val" id="health-indicator">--</div></div>
  1126. <div class="health-line"><div class="name">Runtime Alert</div><div class="val" id="health-alert">--</div></div>
  1127. <div class="health-line"><div class="name">Transitions (D/M/F)</div><div class="val" id="health-transitions">--</div></div>
  1128. <div class="health-line"><div class="name">Fault Count</div><div class="val" id="health-fault-count">--</div></div>
  1129. <div class="health-line"><div class="name">Last Fault</div><div class="val" id="health-last-fault">--</div></div>
  1130. <div class="health-line"><div class="name">Audio Buffer</div><div class="val" id="health-audio">--</div></div>
  1131. <div class="health-line"><div class="name">Buffer Duration</div><div class="val" id="health-buffer-duration">--</div></div>
  1132. <div class="health-line"><div class="name">High Watermark</div><div class="val" id="health-buffer-highwater">--</div></div>
  1133. <div class="health-line"><div class="name">Queue Fill</div><div class="val" id="health-queue-fill">--</div></div>
  1134. <div class="health-line"><div class="name">Underrun Streak</div><div class="val" id="health-underrun-streak">--</div></div>
  1135. <div class="health-line"><div class="name">Last Update</div><div class="val" id="health-last">--</div></div>
  1136. <div class="health-trend">
  1137. <div class="health-trend-label">High Watermark Trend</div>
  1138. <svg class="spark warn" id="spark-high-watermark" viewBox="0 0 160 34" preserveAspectRatio="none"></svg>
  1139. </div>
  1140. <div class="health-trend">
  1141. <div class="health-trend-label">Queue Fill Trend</div>
  1142. <svg class="spark good" id="spark-queue-fill" viewBox="0 0 160 34" preserveAspectRatio="none"></svg>
  1143. </div>
  1144. </div>
  1145. </div>
  1146. <div class="card panel" data-panel-key="shortcuts">
  1147. <div class="panel-head" data-panel>
  1148. <h2>Shortcuts</h2>
  1149. <div class="meta">keyboard</div>
  1150. <span class="chevron">▼</span>
  1151. </div>
  1152. <div class="panel-body">
  1153. <div class="section-note">Fast control, as long as you're not typing in an input field.</div>
  1154. <div class="shortcuts-grid">
  1155. <div>
  1156. <div class="shortcut-line"><span class="name">Start TX</span><span class="keys"><span class="kbd">t</span></span></div>
  1157. <div class="shortcut-line"><span class="name">Stop TX</span><span class="keys"><span class="kbd">Shift</span><span class="kbd">t</span></span></div>
  1158. <div class="shortcut-line"><span class="name">Refresh</span><span class="keys"><span class="kbd">r</span></span></div>
  1159. </div>
  1160. <div>
  1161. <div class="shortcut-line"><span class="name">Next Freq Preset</span><span class="keys"><span class="kbd">]</span></span></div>
  1162. <div class="shortcut-line"><span class="name">Prev Freq Preset</span><span class="keys"><span class="kbd">[</span></span></div>
  1163. <div class="shortcut-line"><span class="name">Apply Draft</span><span class="keys"><span class="kbd">Enter</span></span></div>
  1164. </div>
  1165. </div>
  1166. </div>
  1167. </div>
  1168. <div class="card panel" data-panel-key="danger">
  1169. <div class="panel-head" data-panel>
  1170. <h2>Danger Zone</h2>
  1171. <div class="meta">tx control</div>
  1172. <span class="chevron">▼</span>
  1173. </div>
  1174. <div class="panel-body">
  1175. <div class="section-note">Fast emergency controls. Nothing hidden here — just clearer separation from normal controls.</div>
  1176. <div class="actions-row" style="margin-top:0">
  1177. <button class="danger-btn" id="danger-stop" type="button">Emergency Stop TX</button>
  1178. <button class="danger-btn" id="danger-refresh" type="button">Hard Refresh Runtime</button>
  1179. <button class="danger-btn secondary" id="danger-reset-fault" type="button">Reset Fault</button>
  1180. </div>
  1181. <div class="section-note reset-hint" id="reset-hint">
  1182. Reset Fault moves the runtime back to DEGRADED while the queue settles before running again.
  1183. </div>
  1184. </div>
  1185. </div>
  1186. <div class="card panel" data-panel-key="transition-history">
  1187. <div class="panel-head" data-panel>
  1188. <h2>Transition History</h2>
  1189. <div class="meta">recent state shifts</div>
  1190. <span class="chevron"></span>
  1191. </div>
  1192. <div class="panel-body">
  1193. <div class="section-note">Keeps runtime escalations visible without scrolling the activity log.</div>
  1194. <div class="transition-history" id="transition-history">
  1195. <div class="transition-history-empty">No transitions yet.</div>
  1196. </div>
  1197. </div>
  1198. </div>
  1199. <div class="card panel" data-panel-key="fault-history">
  1200. <div class="panel-head" data-panel>
  1201. <h2>Fault History</h2>
  1202. <div class="meta">recent faults</div>
  1203. <span class="chevron">▼</span>
  1204. </div>
  1205. <div class="panel-body">
  1206. <div class="section-note">Recent fault events for quick ops situational awareness.</div>
  1207. <div class="fault-history" id="fault-history">
  1208. <div class="fault-history-empty">No faults yet.</div>
  1209. </div>
  1210. </div>
  1211. </div>
  1212. <div class="card panel" data-panel-key="log">
  1213. <div class="panel-head" data-panel>
  1214. <h2>Activity Log</h2>
  1215. <div class="meta" id="log-meta">recent events</div>
  1216. <span class="chevron">▼</span>
  1217. </div>
  1218. <div class="panel-body">
  1219. <div class="actions-row" style="margin-top:0;margin-bottom:12px">
  1220. <button class="ghost-btn" id="btn-clear-log" type="button">Clear Log</button>
  1221. </div>
  1222. <div class="log" id="log"><div class="empty-log">No events yet.</div></div>
  1223. </div>
  1224. </div>
  1225. </div>
  1226. </div>
  1227. </div>
  1228. <div class="toast" id="toast"></div>
  1229. <script>
  1230. const $ = (id) => document.getElementById(id);
  1231. const runtimePollMs = 1000;
  1232. const configPollMs = 8000;
  1233. const mobileMq = window.matchMedia('(max-width: 640px)');
  1234. const freqPresetValues = [87.6, 94.5, 99.5, 100.0, 107.9];
  1235. const sparkHistoryLimit = 40;
  1236. const transitionHistoryLimit = 6;
  1237. const state = {
  1238. server: {
  1239. config: null,
  1240. runtime: null,
  1241. lastConfigAt: 0,
  1242. lastRuntimeAt: 0,
  1243. configOk: false,
  1244. runtimeOk: false,
  1245. },
  1246. lastRuntimeState: '',
  1247. draft: {
  1248. frequencyMHz: undefined,
  1249. ps: undefined,
  1250. radioText: undefined,
  1251. },
  1252. errors: {
  1253. frequencyMHz: '',
  1254. ps: '',
  1255. radioText: '',
  1256. },
  1257. dirty: new Set(),
  1258. pendingRequests: 0,
  1259. txBusy: false,
  1260. faultResetBusy: false,
  1261. toggleBusy: {},
  1262. pollersStarted: false,
  1263. mobilePanelsApplied: false,
  1264. charts: {
  1265. audio: [],
  1266. underruns: [],
  1267. tx: [],
  1268. highWatermark: [],
  1269. queueFill: [],
  1270. },
  1271. runtimeTransitions: [],
  1272. freqPresetIndex: 0,
  1273. };
  1274. const fields = {
  1275. frequencyMHz: { section: 'freq', equal: (a,b) => nearlyEqual(a,b,0.0001) },
  1276. ps: { section: 'rds', equal: (a,b) => String(a ?? '') === String(b ?? '') },
  1277. radioText: { section: 'rds', equal: (a,b) => String(a ?? '') === String(b ?? '') },
  1278. };
  1279. function nearlyEqual(a, b, eps = 1e-9) {
  1280. if (a == null && b == null) return true;
  1281. if (a == null || b == null) return false;
  1282. return Math.abs(Number(a) - Number(b)) <= eps;
  1283. }
  1284. function nowTs() { return Date.now(); }
  1285. function serverValue(key) {
  1286. const cfg = state.server.config;
  1287. if (!cfg) return undefined;
  1288. switch (key) {
  1289. case 'frequencyMHz': return cfg.fm?.frequencyMHz;
  1290. case 'ps': return cfg.rds?.ps ?? '';
  1291. case 'radioText': return cfg.rds?.radioText ?? '';
  1292. case 'stereoEnabled': return cfg.fm?.stereoEnabled;
  1293. case 'rdsEnabled': return cfg.rds?.enabled;
  1294. case 'limiterEnabled': return cfg.fm?.limiterEnabled;
  1295. default: return undefined;
  1296. }
  1297. }
  1298. function effectiveValue(key) {
  1299. return state.dirty.has(key) ? state.draft[key] : serverValue(key);
  1300. }
  1301. function validateField(key, value) {
  1302. switch (key) {
  1303. case 'frequencyMHz': {
  1304. if (value == null || Number.isNaN(Number(value))) return 'Enter a valid number.';
  1305. const num = Number(value);
  1306. if (num < 65 || num > 110) return 'Frequency must stay between 65 and 110 MHz.';
  1307. return '';
  1308. }
  1309. case 'ps': {
  1310. const text = String(value ?? '');
  1311. if (text.length > 8) return 'PS is limited to 8 characters.';
  1312. return '';
  1313. }
  1314. case 'radioText': {
  1315. const text = String(value ?? '');
  1316. if (text.length > 64) return 'RadioText is limited to 64 characters.';
  1317. return '';
  1318. }
  1319. default:
  1320. return '';
  1321. }
  1322. }
  1323. function sectionHasErrors(section) {
  1324. return Object.entries(fields).some(([key, meta]) => meta.section === section && state.errors[key]);
  1325. }
  1326. function setDirty(key, value) {
  1327. state.draft[key] = value;
  1328. state.errors[key] = validateField(key, value);
  1329. const current = serverValue(key);
  1330. const equal = !state.errors[key] && fields[key].equal(value, current);
  1331. if (equal) {
  1332. state.dirty.delete(key);
  1333. state.draft[key] = undefined;
  1334. } else {
  1335. state.dirty.add(key);
  1336. }
  1337. if (key === 'frequencyMHz' && typeof value === 'number') syncFreqPresetIndex(value);
  1338. render();
  1339. }
  1340. function clearDirty(keys) {
  1341. for (const key of keys) {
  1342. state.dirty.delete(key);
  1343. state.draft[key] = undefined;
  1344. state.errors[key] = '';
  1345. }
  1346. render();
  1347. }
  1348. function isDirtySection(section) {
  1349. for (const key of state.dirty) {
  1350. if (fields[key]?.section === section) return true;
  1351. }
  1352. return false;
  1353. }
  1354. function getSectionPatch(section) {
  1355. const patch = {};
  1356. for (const key of state.dirty) {
  1357. if (fields[key]?.section === section && !state.errors[key]) patch[key] = state.draft[key];
  1358. }
  1359. return patch;
  1360. }
  1361. async function api(path, opts) {
  1362. const response = await fetch(path, opts);
  1363. const text = await response.text();
  1364. if (!response.ok) {
  1365. throw new Error(text.trim() || `HTTP ${response.status}`);
  1366. }
  1367. if (!text) return {};
  1368. try {
  1369. return JSON.parse(text);
  1370. } catch {
  1371. return { ok: true, raw: text };
  1372. }
  1373. }
  1374. function setConnection(ok, mode) {
  1375. const led = $('led-conn');
  1376. const label = $('conn-label');
  1377. if (ok) {
  1378. led.className = 'led on-green';
  1379. label.textContent = mode || 'connected';
  1380. } else {
  1381. led.className = 'led on-red';
  1382. label.textContent = mode || 'offline';
  1383. }
  1384. }
  1385. async function loadConfig({ silent = false } = {}) {
  1386. try {
  1387. const cfg = await api('/config');
  1388. state.server.config = cfg;
  1389. state.server.configOk = true;
  1390. state.server.lastConfigAt = nowTs();
  1391. syncFreqPresetIndex(cfg.fm?.frequencyMHz);
  1392. setConnection(true, state.pendingRequests > 0 ? 'busy' : 'connected');
  1393. render();
  1394. if (!silent) log('Config synced from server', 'info');
  1395. return cfg;
  1396. } catch (error) {
  1397. state.server.configOk = false;
  1398. if (!state.server.runtimeOk) setConnection(false, 'offline');
  1399. render();
  1400. if (!silent) log('Config load failed: ' + error.message, 'err');
  1401. throw error;
  1402. }
  1403. }
  1404. async function loadRuntime({ silent = true } = {}) {
  1405. try {
  1406. const runtime = await api('/runtime');
  1407. state.server.runtime = runtime;
  1408. state.server.runtimeOk = true;
  1409. state.server.lastRuntimeAt = nowTs();
  1410. const syncedTransitions = syncTransitionHistoryFromEngine(runtime.engine);
  1411. notifyRuntimeTransition(runtime.engine, !syncedTransitions);
  1412. pushHistory(runtime);
  1413. setConnection(true, state.pendingRequests > 0 ? 'busy' : 'connected');
  1414. render();
  1415. return runtime;
  1416. } catch (error) {
  1417. state.server.runtimeOk = false;
  1418. if (!state.server.configOk) setConnection(false, 'offline');
  1419. render();
  1420. if (!silent) log('Runtime load failed: ' + error.message, 'err');
  1421. throw error;
  1422. }
  1423. }
  1424. function pushHistory(runtime) {
  1425. const engine = runtime.engine || {};
  1426. const driver = runtime.driver || {};
  1427. const audio = runtime.audioStream || {};
  1428. pushChart(state.charts.audio, typeof audio.buffered === 'number' ? audio.buffered : 0);
  1429. const highWatermarkDurationSeconds = Number(audio.highWatermarkDurationSeconds);
  1430. const normalizedHighWatermark = Number.isFinite(highWatermarkDurationSeconds) ? highWatermarkDurationSeconds : 0;
  1431. pushChart(state.charts.highWatermark, normalizedHighWatermark);
  1432. const queueFill = Number(engine.queue?.fillLevel ?? 0);
  1433. pushChart(state.charts.queueFill, Number.isFinite(queueFill) ? queueFill : 0);
  1434. pushChart(state.charts.underruns, Number(engine.underruns ?? driver.underruns ?? 0));
  1435. const txState = String(engine.state || 'idle').toLowerCase();
  1436. pushChart(state.charts.tx, txState === 'running' ? 1 : state.txBusy ? 0.55 : 0.05);
  1437. }
  1438. function pushTransitionHistory(from, to, severity) {
  1439. if (!from || !to) return;
  1440. const entry = {
  1441. from: normalizeRuntimeState(from),
  1442. to: normalizeRuntimeState(to),
  1443. severity: severity || 'info',
  1444. time: nowTs(),
  1445. };
  1446. state.runtimeTransitions.unshift(entry);
  1447. if (state.runtimeTransitions.length > transitionHistoryLimit) {
  1448. state.runtimeTransitions.splice(transitionHistoryLimit);
  1449. }
  1450. updateTransitionHistory();
  1451. }
  1452. function transitionEntryTime(value) {
  1453. if (value == null) return nowTs();
  1454. if (typeof value === 'number') return value;
  1455. const parsed = Date.parse(String(value));
  1456. return Number.isNaN(parsed) ? nowTs() : parsed;
  1457. }
  1458. function syncTransitionHistoryFromEngine(engine) {
  1459. const entries = Array.isArray(engine?.transitionHistory) ? engine.transitionHistory : null;
  1460. if (!entries) return false;
  1461. const sliceStart = Math.max(0, entries.length - transitionHistoryLimit);
  1462. const trimmed = entries.slice(sliceStart);
  1463. const normalized = trimmed.map((entry) => ({
  1464. from: normalizeRuntimeState(entry?.from),
  1465. to: normalizeRuntimeState(entry?.to),
  1466. severity: String(entry?.severity || 'info').toLowerCase(),
  1467. time: transitionEntryTime(entry?.time),
  1468. }));
  1469. normalized.reverse();
  1470. state.runtimeTransitions = normalized;
  1471. updateTransitionHistory();
  1472. return true;
  1473. }
  1474. function transitionSeverityClass(severity) {
  1475. switch (String(severity || '').toLowerCase()) {
  1476. case 'err':
  1477. return 'err';
  1478. case 'warn':
  1479. return 'warn';
  1480. case 'ok':
  1481. case 'good':
  1482. return 'good';
  1483. default:
  1484. return 'info';
  1485. }
  1486. }
  1487. function updateTransitionHistory() {
  1488. const container = $('transition-history');
  1489. if (!container) return;
  1490. if (!state.runtimeTransitions.length) {
  1491. container.innerHTML = '<div class="transition-history-empty">No transitions yet.</div>';
  1492. return;
  1493. }
  1494. const rows = state.runtimeTransitions.map((entry) => {
  1495. const when = entry?.time ? new Date(entry.time) : null;
  1496. const timeLabel = when && !Number.isNaN(when.getTime()) ? when.toLocaleTimeString() : '--:--';
  1497. const desc = `${entry.from.toUpperCase()} → ${entry.to.toUpperCase()}`;
  1498. const severityClass = transitionSeverityClass(entry.severity);
  1499. return `<div class="transition-history-entry ${severityClass}"><span class="transition-history-time">${timeLabel}</span><span class="transition-history-desc">${desc}</span></div>`;
  1500. });
  1501. container.innerHTML = rows.join('');
  1502. }
  1503. function pushChart(arr, value) {
  1504. arr.push(Number.isFinite(value) ? value : 0);
  1505. if (arr.length > sparkHistoryLimit) arr.splice(0, arr.length - sparkHistoryLimit);
  1506. }
  1507. function setConnectionBusy() {
  1508. setConnection(true, 'busy');
  1509. }
  1510. function beginRequest() {
  1511. state.pendingRequests += 1;
  1512. setConnectionBusy();
  1513. render();
  1514. }
  1515. function endRequest() {
  1516. state.pendingRequests = Math.max(0, state.pendingRequests - 1);
  1517. if (state.server.configOk || state.server.runtimeOk) {
  1518. setConnection(true, state.pendingRequests > 0 ? 'busy' : 'connected');
  1519. }
  1520. render();
  1521. }
  1522. async function sendPatch(patch, { successMessage = 'Applied', clearKeys = [] } = {}) {
  1523. beginRequest();
  1524. try {
  1525. const result = await api('/config', {
  1526. method: 'POST',
  1527. headers: { 'Content-Type': 'application/json' },
  1528. body: JSON.stringify(patch),
  1529. });
  1530. if (state.server.config) mergeLocalConfigPatch(patch);
  1531. clearDirty(clearKeys);
  1532. render();
  1533. toast(successMessage + (result.live ? ' · live' : ''), 'ok');
  1534. log('PATCH ' + JSON.stringify(patch) + (result.live ? ' [live]' : ' [saved]'), 'ok');
  1535. await Promise.allSettled([
  1536. loadConfig({ silent: true }),
  1537. loadRuntime({ silent: true }),
  1538. ]);
  1539. return result;
  1540. } catch (error) {
  1541. toast(error.message, 'err');
  1542. log('PATCH failed: ' + error.message, 'err');
  1543. throw error;
  1544. } finally {
  1545. endRequest();
  1546. }
  1547. }
  1548. function mergeLocalConfigPatch(patch) {
  1549. const cfg = state.server.config || {};
  1550. cfg.fm ||= {};
  1551. cfg.rds ||= {};
  1552. for (const [key, value] of Object.entries(patch)) {
  1553. switch (key) {
  1554. case 'frequencyMHz': cfg.fm.frequencyMHz = value; break;
  1555. case 'stereoEnabled': cfg.fm.stereoEnabled = value; break;
  1556. case 'limiterEnabled': cfg.fm.limiterEnabled = value; break;
  1557. case 'rdsEnabled': cfg.rds.enabled = value; break;
  1558. case 'ps': cfg.rds.ps = value; break;
  1559. case 'radioText': cfg.rds.radioText = value; break;
  1560. }
  1561. }
  1562. }
  1563. async function applySection(section) {
  1564. if (sectionHasErrors(section)) {
  1565. toast('Fix the highlighted fields first', 'warn');
  1566. log(section.toUpperCase() + ' apply blocked by validation errors', 'warn');
  1567. render();
  1568. return;
  1569. }
  1570. const patch = getSectionPatch(section);
  1571. const keys = Object.keys(patch);
  1572. if (!keys.length) {
  1573. toast('No changes to apply', 'info');
  1574. return;
  1575. }
  1576. let message = 'Applied';
  1577. if (section === 'freq') message = 'Frequency updated';
  1578. if (section === 'rds') message = 'RDS text updated';
  1579. await sendPatch(patch, { successMessage: message, clearKeys: keys });
  1580. }
  1581. function resetSection(section) {
  1582. const keys = Object.keys(fields).filter((key) => fields[key].section === section);
  1583. clearDirty(keys);
  1584. log(section.toUpperCase() + ' draft reset', 'warn');
  1585. toast('Draft reset', 'info');
  1586. }
  1587. async function setToggle(key, nextValue) {
  1588. if (state.toggleBusy[key]) return;
  1589. state.toggleBusy[key] = true;
  1590. render();
  1591. try {
  1592. await sendPatch({ [key]: nextValue }, {
  1593. successMessage: key.replace(/Enabled$/, '') + ' ' + (nextValue ? 'enabled' : 'disabled'),
  1594. clearKeys: [],
  1595. });
  1596. } finally {
  1597. state.toggleBusy[key] = false;
  1598. render();
  1599. }
  1600. }
  1601. async function txAction(action) {
  1602. if (state.txBusy) return;
  1603. state.txBusy = true;
  1604. render();
  1605. beginRequest();
  1606. try {
  1607. await api(`/tx/${action}`, { method: 'POST' });
  1608. toast(action === 'start' ? 'TX started' : 'TX stopped', 'ok');
  1609. log('TX ' + action + ' request accepted', 'ok');
  1610. await Promise.allSettled([
  1611. loadRuntime({ silent: true }),
  1612. loadConfig({ silent: true }),
  1613. ]);
  1614. } catch (error) {
  1615. toast(error.message, 'err');
  1616. log('TX ' + action + ' failed: ' + error.message, 'err');
  1617. } finally {
  1618. state.txBusy = false;
  1619. endRequest();
  1620. render();
  1621. }
  1622. }
  1623. async function resetFaultAction() {
  1624. if (state.faultResetBusy) return;
  1625. state.faultResetBusy = true;
  1626. render();
  1627. beginRequest();
  1628. try {
  1629. await api('/runtime/fault/reset', { method: 'POST' });
  1630. toast('Fault reset', 'ok');
  1631. log('Fault reset request accepted', 'ok');
  1632. await loadRuntime({ silent: true });
  1633. } catch (error) {
  1634. toast(error.message, 'err');
  1635. log('Fault reset failed: ' + error.message, 'err');
  1636. } finally {
  1637. state.faultResetBusy = false;
  1638. endRequest();
  1639. render();
  1640. }
  1641. }
  1642. function fmt(n) {
  1643. if (n == null) return '--';
  1644. if (n >= 1e9) return (n / 1e9).toFixed(2) + 'G';
  1645. if (n >= 1e6) return (n / 1e6).toFixed(2) + 'M';
  1646. if (n >= 1e3) return (n / 1e3).toFixed(1) + 'k';
  1647. return String(n);
  1648. }
  1649. function fmtTime(seconds) {
  1650. if (!seconds || seconds <= 0) return '--';
  1651. const h = Math.floor(seconds / 3600);
  1652. const m = Math.floor((seconds % 3600) / 60);
  1653. const s = Math.floor(seconds % 60);
  1654. if (h > 0) return `${h}h ${m}m`;
  1655. if (m > 0) return `${m}m ${s}s`;
  1656. return `${s}s`;
  1657. }
  1658. function fmtDurationSeconds(value) {
  1659. if (!Number.isFinite(value) || value < 0) return '--';
  1660. if (value >= 1) return `${value.toFixed(2)} s`;
  1661. return `${(value * 1000).toFixed(0)} ms`;
  1662. }
  1663. function fmtBool(v) {
  1664. return v == null ? '--' : (v ? 'ON' : 'OFF');
  1665. }
  1666. function fmtFreq(v) {
  1667. return typeof v === 'number' ? v.toFixed(1) + ' MHz' : '--';
  1668. }
  1669. function fmtPercent(v) {
  1670. if (typeof v !== 'number') return '--';
  1671. return (v * 100).toFixed(0) + '%';
  1672. }
  1673. function ageString(ts) {
  1674. if (!ts) return '--';
  1675. const diff = Math.max(0, Math.floor((nowTs() - ts) / 1000));
  1676. if (diff < 2) return 'just now';
  1677. if (diff < 60) return diff + 's ago';
  1678. const m = Math.floor(diff / 60);
  1679. if (m < 60) return m + 'm ago';
  1680. const h = Math.floor(m / 60);
  1681. return h + 'h ago';
  1682. }
  1683. function updateText(id, text) {
  1684. const el = $(id);
  1685. if (el && el.textContent !== String(text)) el.textContent = text;
  1686. }
  1687. function updateHTML(id, html) {
  1688. const el = $(id);
  1689. if (el && el.innerHTML !== html) el.innerHTML = html;
  1690. }
  1691. function syncDirtyInput(id, key, transform = (v) => v) {
  1692. const el = $(id);
  1693. if (!el) return;
  1694. const dirty = state.dirty.has(key);
  1695. const desired = dirty ? transform(state.draft[key]) : transform(serverValue(key));
  1696. const asString = desired == null ? '' : String(desired);
  1697. const isFocused = document.activeElement === el;
  1698. if (!isFocused || !dirty) {
  1699. if (el.value !== asString) el.value = asString;
  1700. }
  1701. el.classList.toggle('input-dirty', dirty && !state.errors[key]);
  1702. el.classList.toggle('input-error', !!state.errors[key]);
  1703. }
  1704. function renderFieldErrors() {
  1705. renderFieldError('freq-error', state.errors.frequencyMHz);
  1706. renderFieldError('ps-error', state.errors.ps);
  1707. renderFieldError('rt-error', state.errors.radioText);
  1708. }
  1709. function renderFieldError(id, message) {
  1710. const el = $(id);
  1711. el.textContent = message || '';
  1712. el.classList.toggle('show', !!message);
  1713. }
  1714. function setMeter(fillId, textId, ratio, text, mode = 'good') {
  1715. const fill = $(fillId);
  1716. const pct = Math.max(0, Math.min(100, Math.round((ratio ?? 0) * 100)));
  1717. fill.style.width = pct + '%';
  1718. fill.className = 'meter-fill' + (mode === 'warn' ? ' warn' : mode === 'err' ? ' err' : '');
  1719. updateText(textId, text);
  1720. }
  1721. function applyMobilePanelDefaults() {
  1722. if (!mobileMq.matches || state.mobilePanelsApplied) return;
  1723. state.mobilePanelsApplied = true;
  1724. document.querySelectorAll('.panel[data-panel-key]').forEach((panel) => {
  1725. const key = panel.dataset.panelKey;
  1726. const head = panel.querySelector('.panel-head');
  1727. const body = panel.querySelector('.panel-body');
  1728. const keepOpen = key === 'frequency' || key === 'danger';
  1729. head.classList.toggle('collapsed', !keepOpen);
  1730. body.classList.toggle('collapsed', !keepOpen);
  1731. });
  1732. }
  1733. function syncFreqPresetIndex(value) {
  1734. if (typeof value !== 'number') return;
  1735. let closestIndex = 0;
  1736. let closestDistance = Infinity;
  1737. freqPresetValues.forEach((freq, idx) => {
  1738. const dist = Math.abs(freq - value);
  1739. if (dist < closestDistance) {
  1740. closestDistance = dist;
  1741. closestIndex = idx;
  1742. }
  1743. });
  1744. state.freqPresetIndex = closestIndex;
  1745. }
  1746. function cycleFreqPreset(direction) {
  1747. state.freqPresetIndex = (state.freqPresetIndex + direction + freqPresetValues.length) % freqPresetValues.length;
  1748. const next = freqPresetValues[state.freqPresetIndex];
  1749. setDirty('frequencyMHz', next);
  1750. toast(`Preset ${next.toFixed(1)} MHz loaded`, 'info');
  1751. }
  1752. function refreshPresetButtons() {
  1753. const effectiveFreq = effectiveValue('frequencyMHz');
  1754. document.querySelectorAll('[data-freq-preset]').forEach((btn) => {
  1755. const value = Number(btn.dataset.freqPreset);
  1756. btn.classList.toggle('active', typeof effectiveFreq === 'number' && nearlyEqual(value, effectiveFreq, 0.05));
  1757. });
  1758. }
  1759. function updateHeroState(engineState) {
  1760. const hero = $('hero-card');
  1761. hero.classList.remove('tx-live', 'tx-busy');
  1762. if (state.txBusy || ['starting', 'stopping'].includes(engineState)) {
  1763. hero.classList.add('tx-busy');
  1764. } else if (engineState === 'running') {
  1765. hero.classList.add('tx-live');
  1766. }
  1767. }
  1768. function drawSparkline(svgId, values, mode = 'good', maxOverride = null) {
  1769. const svg = $(svgId);
  1770. if (!svg) return;
  1771. svg.className = `spark ${mode}`;
  1772. const width = 160;
  1773. const height = 34;
  1774. const points = values.length ? values : [0, 0];
  1775. const max = maxOverride != null ? maxOverride : Math.max(...points, 1);
  1776. const min = 0;
  1777. const step = points.length <= 1 ? width : width / (points.length - 1);
  1778. const coords = points.map((value, i) => {
  1779. const x = i * step;
  1780. const norm = max === min ? 0 : (value - min) / (max - min || 1);
  1781. const y = height - 4 - norm * (height - 8);
  1782. return [x, y];
  1783. });
  1784. const line = coords.map(([x, y], i) => `${i === 0 ? 'M' : 'L'}${x.toFixed(2)},${y.toFixed(2)}`).join(' ');
  1785. const area = `${line} L ${width},${height} L 0,${height} Z`;
  1786. svg.innerHTML = `<path class="area" d="${area}"></path><path class="line" d="${line}"></path>`;
  1787. }
  1788. function render() {
  1789. const cfg = state.server.config || {};
  1790. const runtime = state.server.runtime || {};
  1791. const engine = runtime.engine || {};
  1792. const driver = runtime.driver || {};
  1793. const audioStream = runtime.audioStream || null;
  1794. const freq = effectiveValue('frequencyMHz') ?? cfg.fm?.frequencyMHz;
  1795. updateHTML('freq-display', `${typeof freq === 'number' ? freq.toFixed(1) : '---.-'}<span class="unit">MHz</span>`);
  1796. updateText('badge-backend', cfg.backend?.kind || cfg.backend || '--');
  1797. updateText('badge-mode', engine.state && engine.state !== 'idle' ? 'TX Active' : 'Control Plane');
  1798. updateText('badge-live', state.server.runtimeOk ? 'Connected' : 'Waiting');
  1799. updateText('t-chunks', fmt(engine.chunksProduced));
  1800. updateText('t-samples', fmt(engine.totalSamples));
  1801. updateText('t-uptime', fmtTime(engine.uptimeSeconds));
  1802. updateText('t-rate', driver.effectiveSampleRateHz ? (driver.effectiveSampleRateHz / 1000).toFixed(0) + 'k' : '--');
  1803. const underruns = engine.underruns ?? driver.underruns;
  1804. const underrunEl = $('t-underruns');
  1805. underrunEl.textContent = underruns == null ? '--' : String(underruns);
  1806. underrunEl.className = 'value' + (underruns > 0 ? ' err' : underruns === 0 ? ' good' : '');
  1807. const txStateValue = String(engine.state || 'idle').toLowerCase();
  1808. const txState = state.txBusy ? 'WORKING…' : txStateValue.toUpperCase();
  1809. const txClass = state.txBusy ? 'working' : txStateValue;
  1810. $('tx-state').textContent = txState;
  1811. $('tx-state').className = 'tx-state ' + txClass;
  1812. updateText('tx-hint', engine.lastError ? `Last error: ${engine.lastError}` : (state.txBusy ? 'Command in progress' : 'Runtime polled every 1s'));
  1813. updateHeroState(txStateValue);
  1814. const startDisabled = state.txBusy || txStateValue === 'running';
  1815. const stopDisabled = state.txBusy || ['idle', 'stopped', ''].includes(txStateValue);
  1816. $('btn-start').disabled = startDisabled;
  1817. $('btn-stop').disabled = stopDisabled;
  1818. $('btn-refresh').disabled = state.pendingRequests > 0;
  1819. $('danger-stop').disabled = stopDisabled;
  1820. $('danger-refresh').disabled = state.pendingRequests > 0;
  1821. const resetFaultBtn = $('danger-reset-fault');
  1822. if (resetFaultBtn) {
  1823. const resetDisabled = state.faultResetBusy || !state.server.runtimeOk;
  1824. resetFaultBtn.disabled = resetDisabled;
  1825. resetFaultBtn.textContent = state.faultResetBusy ? 'Resetting…' : 'Reset Fault';
  1826. }
  1827. syncDirtyInput('freq-slider', 'frequencyMHz', (v) => typeof v === 'number' ? v.toFixed(1) : '100.0');
  1828. syncDirtyInput('freq-num', 'frequencyMHz', (v) => typeof v === 'number' ? v.toFixed(1) : '100.0');
  1829. syncDirtyInput('rds-ps', 'ps', (v) => String(v ?? ''));
  1830. syncDirtyInput('rds-rt', 'radioText', (v) => String(v ?? ''));
  1831. const psValue = String(effectiveValue('ps') ?? cfg.rds?.ps ?? '');
  1832. const rtValue = String(effectiveValue('radioText') ?? cfg.rds?.radioText ?? '');
  1833. updateText('ps-count', psValue.length);
  1834. updateText('rt-count', rtValue.length);
  1835. renderFieldErrors();
  1836. refreshPresetButtons();
  1837. renderToggle('stereoEnabled', 'tog-stereo', 'stereo-label');
  1838. renderToggle('rdsEnabled', 'tog-rds', 'rds-label');
  1839. renderToggle('limiterEnabled', 'tog-limiter', 'limiter-label');
  1840. const freqDirty = isDirtySection('freq');
  1841. $('freq-apply').disabled = !freqDirty || sectionHasErrors('freq');
  1842. $('freq-reset').disabled = !freqDirty;
  1843. const rdsDirty = isDirtySection('rds');
  1844. $('rds-apply').disabled = !rdsDirty || sectionHasErrors('rds');
  1845. $('rds-reset').disabled = !rdsDirty;
  1846. updateText('freq-meta', sectionHasErrors('freq') ? 'Validation error' : (freqDirty ? 'Unsaved changes' : 'Live-tunable'));
  1847. updateText('rds-meta', sectionHasErrors('rds') ? 'Validation error' : (rdsDirty ? `${Object.keys(getSectionPatch('rds')).length} unsaved` : 'PS + RT'));
  1848. updateText('info-backend', cfg.backend?.kind || cfg.backend || '--');
  1849. updateText('info-freq', fmtFreq(cfg.fm?.frequencyMHz));
  1850. updateText('info-preemph', cfg.fm?.preEmphasisTauUS ? `${cfg.fm.preEmphasisTauUS} µs` : 'Off');
  1851. updateText('info-fmmod', fmtBool(cfg.fm?.fmModulationEnabled));
  1852. updateText('info-live', engine.state ? `${String(engine.state).toUpperCase()} / ${state.server.runtimeOk ? 'runtime ok' : 'runtime pending'}` : (state.server.configOk ? 'config only' : '--'));
  1853. updateHealth(engine, driver, audioStream);
  1854. updateFaultHistory(engine);
  1855. updateTransitionHistory();
  1856. updateResetHint(engine);
  1857. updateMeters(engine, driver, audioStream);
  1858. const highWatermarkDurationSecondsRaw = audioStream?.highWatermarkDurationSeconds;
  1859. const highWatermarkDurationSeconds = Number(highWatermarkDurationSecondsRaw);
  1860. const highWatermarkFramesRaw = audioStream?.highWatermark;
  1861. const highWatermarkFrames = Number.isFinite(Number(highWatermarkFramesRaw)) ? Number(highWatermarkFramesRaw) : 0;
  1862. const capacityRaw = audioStream?.capacity;
  1863. const capacity = Number.isFinite(Number(capacityRaw)) ? Number(capacityRaw) : 0;
  1864. const bufferedDurationSecondsRaw = audioStream?.bufferedDurationSeconds;
  1865. const bufferedDurationSeconds = Number(bufferedDurationSecondsRaw);
  1866. const hasBufferedDuration = Number.isFinite(bufferedDurationSeconds);
  1867. const hasHighWatermarkDuration = Number.isFinite(highWatermarkDurationSeconds);
  1868. const highWatermarkRatio = capacity > 0 ? Math.min(1, highWatermarkFrames / capacity) : 0;
  1869. let highWatermarkMode = 'good';
  1870. if (highWatermarkRatio >= 0.95) highWatermarkMode = 'err';
  1871. else if (highWatermarkRatio >= 0.65) highWatermarkMode = 'warn';
  1872. const sparkHighWatermarkMax = Math.max(
  1873. 1,
  1874. hasHighWatermarkDuration ? highWatermarkDurationSeconds : 0,
  1875. hasBufferedDuration ? bufferedDurationSeconds : 0
  1876. );
  1877. const queueHealthRaw = String(engine.queue?.health || '').toLowerCase();
  1878. let queueSparkMode = 'good';
  1879. if (queueHealthRaw === 'critical') queueSparkMode = 'err';
  1880. else if (queueHealthRaw === 'low') queueSparkMode = 'warn';
  1881. drawSparkline('spark-audio', state.charts.audio, 'good', 1);
  1882. drawSparkline('spark-high-watermark', state.charts.highWatermark, highWatermarkMode, sparkHighWatermarkMax);
  1883. drawSparkline('spark-queue-fill', state.charts.queueFill, queueSparkMode, 1);
  1884. drawSparkline('spark-underruns', state.charts.underruns, underruns > 0 ? 'err' : 'warn');
  1885. drawSparkline('spark-tx', state.charts.tx, txStateValue === 'running' ? 'good' : 'warn', 1);
  1886. applyMobilePanelDefaults();
  1887. }
  1888. function renderToggle(key, toggleId, labelId) {
  1889. const on = !!serverValue(key);
  1890. const busy = !!state.toggleBusy[key];
  1891. const el = $(toggleId);
  1892. el.className = 'toggle' + (on ? ' on' : '') + (busy ? ' busy' : '');
  1893. el.setAttribute('aria-checked', on ? 'true' : 'false');
  1894. updateText(labelId, busy ? '...' : (on ? 'ON' : 'OFF'));
  1895. }
  1896. function runtimeStateClass(engineState) {
  1897. const normalized = String(engineState || '').toLowerCase();
  1898. if (!normalized) {
  1899. return 'warn';
  1900. }
  1901. switch (normalized) {
  1902. case 'faulted':
  1903. return 'err';
  1904. case 'muted':
  1905. case 'degraded':
  1906. case 'prebuffering':
  1907. case 'arming':
  1908. case 'stopping':
  1909. case 'idle':
  1910. case 'unknown':
  1911. return 'warn';
  1912. default:
  1913. return 'good';
  1914. }
  1915. }
  1916. function normalizeRuntimeState(stateName) {
  1917. const normalized = (typeof stateName === 'string' ? stateName.trim().toLowerCase() : '');
  1918. return normalized || 'idle';
  1919. }
  1920. function runtimeStateSeverity(stateName) {
  1921. const normalized = normalizeRuntimeState(stateName);
  1922. switch (normalized) {
  1923. case 'running':
  1924. return 'ok';
  1925. case 'degraded':
  1926. case 'muted':
  1927. return 'warn';
  1928. case 'faulted':
  1929. return 'err';
  1930. default:
  1931. return 'info';
  1932. }
  1933. }
  1934. function notifyRuntimeTransition(engine, pushHistory = true) {
  1935. if (!engine) return;
  1936. const next = normalizeRuntimeState(engine.state);
  1937. const prev = state.lastRuntimeState;
  1938. state.lastRuntimeState = next;
  1939. if (!prev || prev === next) return;
  1940. const severity = runtimeStateSeverity(next);
  1941. if (pushHistory) {
  1942. pushTransitionHistory(prev, next, severity);
  1943. }
  1944. const message = `Runtime ${prev.toUpperCase()} → ${next.toUpperCase()}`;
  1945. const logLevel = severity === 'err' ? 'err' : (severity === 'warn' ? 'warn' : 'info');
  1946. toast(message, severity);
  1947. log(message, logLevel);
  1948. }
  1949. function updateHealth(engine, driver, audioStream) {
  1950. engine = engine || {};
  1951. driver = driver || {};
  1952. updateText('health-http', state.server.configOk ? 'OK' : 'OFFLINE');
  1953. $('health-http').className = 'val ' + (state.server.configOk ? 'good' : 'err');
  1954. let runtimeLabel = 'WAITING';
  1955. let runtimeClass = 'warn';
  1956. if (state.server.runtimeOk) {
  1957. const engineStateName = String(engine.state || 'unknown');
  1958. runtimeLabel = engineStateName.toUpperCase();
  1959. runtimeClass = runtimeStateClass(engineStateName);
  1960. }
  1961. updateText('health-runtime', runtimeLabel);
  1962. $('health-runtime').className = 'val ' + runtimeClass;
  1963. const durationSeconds = Number(engine.runtimeStateDurationSeconds);
  1964. const durationLabel = Number.isFinite(durationSeconds) && durationSeconds > 0 ? fmtTime(durationSeconds) : '--';
  1965. updateText('health-state-age', durationLabel);
  1966. const stateAgeEl = $('health-state-age');
  1967. if (stateAgeEl) {
  1968. stateAgeEl.className = 'val ' + runtimeClass;
  1969. }
  1970. const runtimeIndicator = engine.runtimeIndicator;
  1971. const indicatorLabels = {
  1972. normal: 'Normal',
  1973. degraded: 'Degraded',
  1974. queueCritical: 'Queue critical',
  1975. };
  1976. const indicatorText = indicatorLabels[runtimeIndicator] || (runtimeIndicator ? runtimeIndicator : '--');
  1977. let indicatorSeverity = '';
  1978. if (runtimeIndicator === 'queueCritical') indicatorSeverity = 'err';
  1979. else if (runtimeIndicator === 'degraded') indicatorSeverity = 'warn';
  1980. else if (runtimeIndicator === 'normal') indicatorSeverity = 'good';
  1981. const indicatorEl = $('health-indicator');
  1982. if (indicatorEl) {
  1983. indicatorEl.className = 'val' + (indicatorSeverity ? ' ' + indicatorSeverity : '');
  1984. }
  1985. updateText('health-indicator', indicatorText);
  1986. const runtimeAlertRaw = (engine.runtimeAlert || '').trim();
  1987. const hasAlert = !!runtimeAlertRaw;
  1988. const alertEl = $('health-alert');
  1989. if (alertEl) {
  1990. alertEl.className = 'val ' + (hasAlert ? 'warn' : 'good');
  1991. }
  1992. updateText('health-alert', hasAlert ? runtimeAlertRaw : 'None');
  1993. let audioLabel = 'N/A';
  1994. let audioClass = 'val';
  1995. if (audioStream) {
  1996. const fill = typeof audioStream.buffered === 'number' ? audioStream.buffered : null;
  1997. audioLabel = fill == null ? 'Unknown' : fmtPercent(fill);
  1998. if (fill == null) audioClass = 'val';
  1999. else if (fill < 0.05) audioClass = 'val err';
  2000. else if (fill < 0.2) audioClass = 'val warn';
  2001. else audioClass = 'val good';
  2002. }
  2003. updateText('health-audio', audioLabel);
  2004. $('health-audio').className = audioClass;
  2005. const bufferedDurationSeconds = Number(audioStream?.bufferedDurationSeconds);
  2006. updateText('health-buffer-duration', fmtDurationSeconds(bufferedDurationSeconds));
  2007. const highWatermarkRaw = audioStream?.highWatermark;
  2008. const highWatermarkFrames = Number.isFinite(Number(highWatermarkRaw)) ? Number(highWatermarkRaw) : null;
  2009. const highWatermarkDurationRaw = audioStream?.highWatermarkDurationSeconds;
  2010. const highWatermarkDuration = Number.isFinite(Number(highWatermarkDurationRaw)) ? Number(highWatermarkDurationRaw) : null;
  2011. let highWatermarkLabel = '--';
  2012. if (highWatermarkDuration !== null) {
  2013. highWatermarkLabel = fmtDurationSeconds(highWatermarkDuration);
  2014. if (highWatermarkFrames !== null) {
  2015. highWatermarkLabel += ` (${highWatermarkFrames} frames)`;
  2016. }
  2017. } else if (highWatermarkFrames !== null) {
  2018. highWatermarkLabel = `${highWatermarkFrames} frames`;
  2019. }
  2020. updateText('health-buffer-highwater', highWatermarkLabel);
  2021. const queueFill = Number(engine.queue?.fillLevel);
  2022. const queueHealthRaw = String(engine.queue?.health || '').toLowerCase();
  2023. const queueHealthLabel = queueHealthRaw ? queueHealthRaw[0].toUpperCase() + queueHealthRaw.slice(1) : '';
  2024. let queueFillLabel = '--';
  2025. if (Number.isFinite(queueFill)) {
  2026. queueFillLabel = fmtPercent(queueFill);
  2027. if (queueHealthLabel) queueFillLabel += ` · ${queueHealthLabel}`;
  2028. } else if (queueHealthLabel) {
  2029. queueFillLabel = queueHealthLabel;
  2030. }
  2031. updateText('health-queue-fill', queueFillLabel);
  2032. const queueFillEl = $('health-queue-fill');
  2033. if (queueFillEl) {
  2034. let queueFillClass = 'good';
  2035. if (queueHealthRaw === 'critical') queueFillClass = 'err';
  2036. else if (queueHealthRaw === 'low') queueFillClass = 'warn';
  2037. queueFillEl.className = 'val ' + queueFillClass;
  2038. }
  2039. const streakEl = $('health-underrun-streak');
  2040. if (streakEl) {
  2041. const streakRaw = driver?.underrunStreak;
  2042. const streakMaxRaw = driver?.maxUnderrunStreak;
  2043. const streakCurrent = Number.isFinite(Number(streakRaw)) ? Number(streakRaw) : null;
  2044. const streakMax = Number.isFinite(Number(streakMaxRaw)) ? Number(streakMaxRaw) : null;
  2045. let streakLabel = '--';
  2046. if (streakCurrent != null) {
  2047. streakLabel = String(streakCurrent);
  2048. if (streakMax != null) {
  2049. streakLabel += ` (max ${streakMax})`;
  2050. }
  2051. } else if (streakMax != null) {
  2052. streakLabel = `Max ${streakMax}`;
  2053. }
  2054. let streakSeverity = '';
  2055. if (streakCurrent != null || streakMax != null) {
  2056. const highestStreak = Math.max(
  2057. streakCurrent != null ? streakCurrent : 0,
  2058. streakMax != null ? streakMax : 0
  2059. );
  2060. if (highestStreak >= 6) streakSeverity = ' err';
  2061. else if (highestStreak > 0) streakSeverity = ' warn';
  2062. else streakSeverity = ' good';
  2063. }
  2064. streakEl.textContent = streakLabel;
  2065. streakEl.className = 'val' + streakSeverity;
  2066. }
  2067. const last = Math.max(state.server.lastConfigAt || 0, state.server.lastRuntimeAt || 0);
  2068. updateText('health-last', ageString(last));
  2069. const transitionsAvailable = engine.degradedTransitions != null || engine.mutedTransitions != null || engine.faultedTransitions != null;
  2070. const transitionsText = transitionsAvailable ? `${Number(engine.degradedTransitions ?? 0)} / ${Number(engine.mutedTransitions ?? 0)} / ${Number(engine.faultedTransitions ?? 0)}` : '--';
  2071. updateText('health-transitions', transitionsText);
  2072. const faultCountValue = engine.faultCount != null ? Number(engine.faultCount) : 0;
  2073. const hasFaultCount = engine.faultCount != null;
  2074. updateText('health-fault-count', hasFaultCount ? String(faultCountValue) : '--');
  2075. const faultCountEl = $('health-fault-count');
  2076. if (faultCountEl) {
  2077. faultCountEl.className = 'val' + (hasFaultCount ? (faultCountValue > 0 ? ' warn' : ' good') : '');
  2078. }
  2079. const lastFaultEl = $('health-last-fault');
  2080. const lastFault = engine.lastFault;
  2081. if (lastFaultEl) {
  2082. if (lastFault) {
  2083. const severity = String(lastFault.severity || '').toLowerCase();
  2084. const severityClass = severity === 'faulted' ? 'err' : 'warn';
  2085. const severityLabel = (lastFault.severity || 'Fault').toUpperCase();
  2086. const reasonLabel = lastFault.reason ? ` ${lastFault.reason}` : '';
  2087. const messageLabel = lastFault.message ? ` - ${lastFault.message}` : '';
  2088. let whenLabel = '';
  2089. if (lastFault.time) {
  2090. const parsed = new Date(lastFault.time);
  2091. if (!Number.isNaN(parsed.getTime())) {
  2092. whenLabel = ` @ ${parsed.toLocaleTimeString()}`;
  2093. }
  2094. }
  2095. const title = `${severityLabel}${reasonLabel}`;
  2096. updateText('health-last-fault', `${title}${messageLabel}${whenLabel}`);
  2097. lastFaultEl.className = 'val ' + severityClass;
  2098. } else {
  2099. lastFaultEl.className = 'val good';
  2100. updateText('health-last-fault', 'None');
  2101. }
  2102. }
  2103. }
  2104. function updateFaultHistory(engine) {
  2105. const container = $('fault-history');
  2106. if (!container) return;
  2107. const history = Array.isArray(engine?.faultHistory) ? engine.faultHistory : [];
  2108. if (!history.length) {
  2109. container.innerHTML = '<div class="fault-history-empty">No faults recorded yet.</div>';
  2110. return;
  2111. }
  2112. const rows = history.slice().reverse().map((entry) => {
  2113. const when = entry?.time ? new Date(entry.time) : null;
  2114. const timeLabel = when && !Number.isNaN(when.getTime()) ? when.toLocaleTimeString() : '--:--';
  2115. const severity = String(entry?.severity || 'warn').toLowerCase();
  2116. const severityLabel = String(entry?.severity || 'Fault').toUpperCase();
  2117. const reasonLabel = entry?.reason ? ` ${entry.reason}` : '';
  2118. const messageLabel = entry?.message ? ` · ${entry.message}` : '';
  2119. return `<div class="fault-history-entry ${severity}"><span class="fault-history-time">${timeLabel}</span><span class="fault-history-desc">${severityLabel}${reasonLabel}${messageLabel}</span></div>`;
  2120. });
  2121. container.innerHTML = rows.join('');
  2122. }
  2123. function updateResetHint(engine) {
  2124. const hint = $('reset-hint');
  2125. if (!hint) return;
  2126. const stateName = String(engine?.state || '').toLowerCase();
  2127. let text = 'Manual fault reset drops runtime to DEGRADED while the queue recovers.';
  2128. if (stateName === 'faulted') {
  2129. text = 'Faulted: reset moves runtime back to DEGRADED until the queue settles.';
  2130. } else if (stateName === 'muted' || stateName === 'degraded') {
  2131. text = 'Reset Fault keeps the runtime in DEGRADED so the queue can recover before running again.';
  2132. }
  2133. const durationSeconds = Number(engine?.runtimeStateDurationSeconds);
  2134. const durationLabel = Number.isFinite(durationSeconds) && durationSeconds > 0 ? fmtTime(durationSeconds) : null;
  2135. const ageHint = durationLabel ? ` State age ${durationLabel}.` : '';
  2136. hint.textContent = text + ageHint;
  2137. }
  2138. function updateMeters(engine, driver, audioStream) {
  2139. if (audioStream && typeof audioStream.buffered === 'number') {
  2140. const ratio = Math.max(0, Math.min(1, audioStream.buffered));
  2141. const mode = ratio < 0.05 ? 'err' : ratio < 0.2 ? 'warn' : 'good';
  2142. setMeter('meter-audio-fill', 'meter-audio-text', ratio, fmtPercent(ratio), mode);
  2143. } else {
  2144. setMeter('meter-audio-fill', 'meter-audio-text', 0, 'N/A', 'warn');
  2145. }
  2146. const underruns = Number(engine.underruns ?? driver.underruns ?? 0);
  2147. const healthRatio = underruns <= 0 ? 1 : Math.max(0, 1 - Math.min(underruns, 10) / 10);
  2148. const healthMode = underruns === 0 ? 'good' : underruns < 3 ? 'warn' : 'err';
  2149. setMeter('meter-stream-fill', 'meter-stream-text', healthRatio, underruns === 0 ? 'Clean' : `${underruns} underrun${underruns === 1 ? '' : 's'}`, healthMode);
  2150. const txState = String(engine.state || 'idle').toLowerCase();
  2151. const activeRatio = txState === 'running' ? 1 : state.txBusy ? 0.55 : 0.08;
  2152. const activeMode = txState === 'running' ? 'good' : state.txBusy ? 'warn' : 'err';
  2153. const activeText = txState === 'running' ? 'Live' : state.txBusy ? 'Working' : 'Idle';
  2154. setMeter('meter-tx-fill', 'meter-tx-text', activeRatio, activeText, activeMode);
  2155. }
  2156. function toast(msg, type = 'info') {
  2157. const t = $('toast');
  2158. t.textContent = msg;
  2159. t.className = 'toast ' + type + ' show';
  2160. clearTimeout(t._timer);
  2161. t._timer = setTimeout(() => t.classList.remove('show'), 2600);
  2162. }
  2163. function log(message, type = '') {
  2164. const logEl = $('log');
  2165. const empty = logEl.querySelector('.empty-log');
  2166. if (empty) empty.remove();
  2167. const row = document.createElement('div');
  2168. row.className = 'entry ' + type;
  2169. row.textContent = `${new Date().toLocaleTimeString()} ${message}`;
  2170. logEl.appendChild(row);
  2171. while (logEl.children.length > 250) logEl.removeChild(logEl.firstChild);
  2172. logEl.scrollTop = logEl.scrollHeight;
  2173. }
  2174. function bindPanels() {
  2175. document.querySelectorAll('[data-panel]').forEach((head) => {
  2176. head.addEventListener('click', () => {
  2177. head.classList.toggle('collapsed');
  2178. head.nextElementSibling.classList.toggle('collapsed');
  2179. });
  2180. });
  2181. }
  2182. function bindInputs() {
  2183. $('freq-slider').addEventListener('input', (e) => {
  2184. const value = Number(e.target.value);
  2185. setDirty('frequencyMHz', value);
  2186. });
  2187. $('freq-num').addEventListener('input', (e) => {
  2188. const value = Number(e.target.value);
  2189. if (!Number.isNaN(value)) setDirty('frequencyMHz', value);
  2190. else {
  2191. state.errors.frequencyMHz = 'Enter a valid number.';
  2192. render();
  2193. }
  2194. });
  2195. $('rds-ps').addEventListener('input', (e) => setDirty('ps', e.target.value.toUpperCase().slice(0, 8)));
  2196. $('rds-rt').addEventListener('input', (e) => setDirty('radioText', e.target.value.slice(0, 64)));
  2197. $('freq-apply').addEventListener('click', () => applySection('freq'));
  2198. $('rds-apply').addEventListener('click', () => applySection('rds'));
  2199. $('freq-reset').addEventListener('click', () => resetSection('freq'));
  2200. $('rds-reset').addEventListener('click', () => resetSection('rds'));
  2201. $('btn-start').addEventListener('click', () => txAction('start'));
  2202. $('btn-stop').addEventListener('click', () => txAction('stop'));
  2203. $('danger-stop').addEventListener('click', () => txAction('stop'));
  2204. $('btn-refresh').addEventListener('click', manualRefresh);
  2205. $('danger-refresh').addEventListener('click', manualRefresh);
  2206. $('danger-reset-fault').addEventListener('click', () => resetFaultAction());
  2207. document.querySelectorAll('.toggle[data-toggle]').forEach((toggle) => {
  2208. const key = toggle.dataset.toggle;
  2209. const handler = () => setToggle(key, !serverValue(key));
  2210. toggle.addEventListener('click', handler);
  2211. toggle.addEventListener('keydown', (e) => {
  2212. if (e.key === 'Enter' || e.key === ' ') {
  2213. e.preventDefault();
  2214. handler();
  2215. }
  2216. });
  2217. });
  2218. document.querySelectorAll('[data-freq-preset]').forEach((btn) => {
  2219. btn.addEventListener('click', () => {
  2220. const value = Number(btn.dataset.freqPreset);
  2221. setDirty('frequencyMHz', value);
  2222. toast(`Frequency preset ${value.toFixed(1)} MHz loaded`, 'info');
  2223. });
  2224. });
  2225. document.querySelectorAll('[data-rds-ps]').forEach((btn) => {
  2226. btn.addEventListener('click', () => {
  2227. setDirty('ps', btn.dataset.rdsPs || '');
  2228. setDirty('radioText', btn.dataset.rdsRt || '');
  2229. toast('RDS preset loaded', 'info');
  2230. });
  2231. });
  2232. $('btn-clear-log').addEventListener('click', () => {
  2233. $('log').innerHTML = '<div class="empty-log">No events yet.</div>';
  2234. toast('Log cleared', 'info');
  2235. });
  2236. }
  2237. async function manualRefresh() {
  2238. beginRequest();
  2239. try {
  2240. await Promise.allSettled([
  2241. loadConfig({ silent: true }),
  2242. loadRuntime({ silent: true }),
  2243. ]);
  2244. toast('Refreshed', 'info');
  2245. log('Manual refresh completed', 'info');
  2246. } finally {
  2247. endRequest();
  2248. }
  2249. }
  2250. function startPollers() {
  2251. if (state.pollersStarted) return;
  2252. state.pollersStarted = true;
  2253. setInterval(() => { loadRuntime({ silent: true }); }, runtimePollMs);
  2254. setInterval(() => { loadConfig({ silent: true }); }, configPollMs);
  2255. }
  2256. function bindResponsiveBehavior() {
  2257. const listener = () => {
  2258. if (!mobileMq.matches) {
  2259. state.mobilePanelsApplied = false;
  2260. return;
  2261. }
  2262. applyMobilePanelDefaults();
  2263. };
  2264. if (mobileMq.addEventListener) mobileMq.addEventListener('change', listener);
  2265. else mobileMq.addListener(listener);
  2266. }
  2267. function isTypingContext(target) {
  2268. if (!target) return false;
  2269. const tag = (target.tagName || '').toLowerCase();
  2270. return tag === 'input' || tag === 'textarea' || target.isContentEditable;
  2271. }
  2272. function bindKeyboardShortcuts() {
  2273. window.addEventListener('keydown', (e) => {
  2274. if (isTypingContext(e.target)) {
  2275. if (e.key !== 'Enter') return;
  2276. if (state.dirty.has('frequencyMHz')) {
  2277. e.preventDefault();
  2278. applySection('freq');
  2279. } else if (isDirtySection('rds')) {
  2280. e.preventDefault();
  2281. applySection('rds');
  2282. }
  2283. return;
  2284. }
  2285. if (e.key === 't' && !e.shiftKey) {
  2286. e.preventDefault();
  2287. txAction('start');
  2288. return;
  2289. }
  2290. if ((e.key === 'T') || (e.key === 't' && e.shiftKey)) {
  2291. e.preventDefault();
  2292. txAction('stop');
  2293. return;
  2294. }
  2295. if (e.key.toLowerCase() === 'r') {
  2296. e.preventDefault();
  2297. manualRefresh();
  2298. return;
  2299. }
  2300. if (e.key === '[') {
  2301. e.preventDefault();
  2302. cycleFreqPreset(-1);
  2303. return;
  2304. }
  2305. if (e.key === ']') {
  2306. e.preventDefault();
  2307. cycleFreqPreset(1);
  2308. return;
  2309. }
  2310. if (e.key === 'Enter') {
  2311. e.preventDefault();
  2312. if (state.dirty.has('frequencyMHz')) applySection('freq');
  2313. else if (isDirtySection('rds')) applySection('rds');
  2314. }
  2315. });
  2316. }
  2317. async function init() {
  2318. bindPanels();
  2319. bindInputs();
  2320. bindResponsiveBehavior();
  2321. bindKeyboardShortcuts();
  2322. render();
  2323. log('fm-rds-tx control UI booting', 'info');
  2324. await Promise.allSettled([
  2325. loadConfig({ silent: false }),
  2326. loadRuntime({ silent: true }),
  2327. ]);
  2328. render();
  2329. startPollers();
  2330. log('Polling active: runtime 1s, config 8s', 'ok');
  2331. log('Keyboard shortcuts armed', 'info');
  2332. }
  2333. init();
  2334. </script>
  2335. </body>
  2336. </html>