Go-based FM stereo transmitter with RDS, Windows-first and cross-platform
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

2687 lines
85KB

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