Go-based FM stereo transmitter with RDS, Windows-first and cross-platform
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

2592 Zeilen
82KB

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