settings.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. // Constants for log message types
  2. const LOG_TYPE = {
  3. SUCCESS: 'success',
  4. WARNING: 'warning',
  5. ERROR: 'error',
  6. INFO: 'info',
  7. DEBUG: 'debug'
  8. };
  9. // Constants for cache
  10. const CACHE_KEYS = {
  11. CONNECTION_STATUS: 'connection_status',
  12. LAST_UPDATE: 'last_status_update'
  13. };
  14. const CACHE_DURATION = 5000; // 5 seconds cache duration
  15. // Function to log messages
  16. function logMessage(message, type = LOG_TYPE.DEBUG) {
  17. console.log(`[${type}] ${message}`);
  18. }
  19. // Function to get cached connection status
  20. function getCachedConnectionStatus() {
  21. const cachedData = localStorage.getItem(CACHE_KEYS.CONNECTION_STATUS);
  22. const lastUpdate = localStorage.getItem(CACHE_KEYS.LAST_UPDATE);
  23. if (cachedData && lastUpdate) {
  24. const now = Date.now();
  25. const cacheAge = now - parseInt(lastUpdate);
  26. if (cacheAge < CACHE_DURATION) {
  27. return JSON.parse(cachedData);
  28. }
  29. }
  30. return null;
  31. }
  32. // Function to set cached connection status
  33. function setCachedConnectionStatus(data) {
  34. localStorage.setItem(CACHE_KEYS.CONNECTION_STATUS, JSON.stringify(data));
  35. localStorage.setItem(CACHE_KEYS.LAST_UPDATE, Date.now().toString());
  36. }
  37. // Function to update serial connection status
  38. async function updateSerialStatus(forceUpdate = false) {
  39. try {
  40. // Check cache first unless force update is requested
  41. if (!forceUpdate) {
  42. const cachedData = getCachedConnectionStatus();
  43. if (cachedData) {
  44. updateConnectionUI(cachedData);
  45. return;
  46. }
  47. }
  48. const response = await fetch('/serial_status');
  49. if (response.ok) {
  50. const data = await response.json();
  51. setCachedConnectionStatus(data);
  52. updateConnectionUI(data);
  53. }
  54. } catch (error) {
  55. logMessage(`Error checking serial status: ${error.message}`, LOG_TYPE.ERROR);
  56. }
  57. }
  58. // Function to update UI based on connection status
  59. function updateConnectionUI(data) {
  60. const statusElement = document.getElementById('serialStatus');
  61. const iconElement = document.querySelector('.material-icons.text-3xl');
  62. const disconnectButton = document.getElementById('disconnectButton');
  63. const portSelectionDiv = document.getElementById('portSelectionDiv');
  64. if (statusElement && iconElement) {
  65. if (data.connected) {
  66. statusElement.textContent = `Connected to ${data.port || 'unknown port'}`;
  67. statusElement.className = 'text-green-500 text-sm font-medium leading-normal';
  68. iconElement.textContent = 'usb';
  69. if (disconnectButton) {
  70. disconnectButton.hidden = false;
  71. }
  72. if (portSelectionDiv) {
  73. portSelectionDiv.hidden = true;
  74. }
  75. } else {
  76. statusElement.textContent = 'Disconnected';
  77. statusElement.className = 'text-red-500 text-sm font-medium leading-normal';
  78. iconElement.textContent = 'usb_off';
  79. if (disconnectButton) {
  80. disconnectButton.hidden = true;
  81. }
  82. if (portSelectionDiv) {
  83. portSelectionDiv.hidden = false;
  84. }
  85. }
  86. }
  87. }
  88. // Function to update available serial ports
  89. async function updateSerialPorts() {
  90. try {
  91. const response = await fetch('/list_serial_ports');
  92. if (response.ok) {
  93. const ports = await response.json();
  94. const portsElement = document.getElementById('availablePorts');
  95. const portSelect = document.getElementById('portSelect');
  96. if (portsElement) {
  97. portsElement.textContent = ports.length > 0 ? ports.join(', ') : 'No ports available';
  98. }
  99. if (portSelect) {
  100. // Clear existing options except the first one
  101. while (portSelect.options.length > 1) {
  102. portSelect.remove(1);
  103. }
  104. // Add new options
  105. ports.forEach(port => {
  106. const option = document.createElement('option');
  107. option.value = port;
  108. option.textContent = port;
  109. portSelect.appendChild(option);
  110. });
  111. // If there's exactly one port available, select and connect to it
  112. if (ports.length === 1) {
  113. portSelect.value = ports[0];
  114. // Trigger connect button click
  115. const connectButton = document.getElementById('connectButton');
  116. if (connectButton) {
  117. connectButton.click();
  118. }
  119. }
  120. }
  121. }
  122. } catch (error) {
  123. logMessage(`Error fetching serial ports: ${error.message}`, LOG_TYPE.ERROR);
  124. }
  125. }
  126. function setWledButtonState(isSet) {
  127. const saveWledConfig = document.getElementById('saveWledConfig');
  128. if (!saveWledConfig) return;
  129. if (isSet) {
  130. saveWledConfig.className = 'flex items-center justify-center gap-2 min-w-[100px] max-w-[480px] cursor-pointer rounded-lg h-10 px-4 bg-red-600 hover:bg-red-700 text-white text-sm font-medium leading-normal tracking-[0.015em] transition-colors';
  131. saveWledConfig.innerHTML = '<span class="material-icons text-lg">close</span><span class="truncate">Clear WLED IP</span>';
  132. } else {
  133. saveWledConfig.className = 'flex items-center justify-center gap-2 min-w-[100px] max-w-[480px] cursor-pointer rounded-lg h-10 px-4 bg-sky-600 hover:bg-sky-700 text-white text-sm font-medium leading-normal tracking-[0.015em] transition-colors';
  134. saveWledConfig.innerHTML = '<span class="material-icons text-lg">save</span><span class="truncate">Save Configuration</span>';
  135. }
  136. }
  137. // Initialize settings page
  138. document.addEventListener('DOMContentLoaded', async () => {
  139. // Initialize UI with default disconnected state
  140. updateConnectionUI({ connected: false });
  141. // Load all data asynchronously
  142. Promise.all([
  143. // Check connection status
  144. fetch('/serial_status').then(response => response.json()).catch(() => ({ connected: false })),
  145. // Load current WLED IP
  146. fetch('/get_wled_ip').then(response => response.json()).catch(() => ({ wled_ip: null })),
  147. // Load current version and check for updates
  148. fetch('/api/version').then(response => response.json()).catch(() => ({ current: '1.0.0', latest: '1.0.0', update_available: false })),
  149. // Load available serial ports
  150. fetch('/list_serial_ports').then(response => response.json()).catch(() => [])
  151. ]).then(([statusData, wledData, updateData, ports]) => {
  152. // Update connection status
  153. setCachedConnectionStatus(statusData);
  154. updateConnectionUI(statusData);
  155. // Update WLED IP
  156. if (wledData.wled_ip) {
  157. document.getElementById('wledIpInput').value = wledData.wled_ip;
  158. setWledButtonState(true);
  159. } else {
  160. setWledButtonState(false);
  161. }
  162. // Update version display
  163. const currentVersionText = document.getElementById('currentVersionText');
  164. const latestVersionText = document.getElementById('latestVersionText');
  165. const updateButton = document.getElementById('updateSoftware');
  166. const updateIcon = document.getElementById('updateIcon');
  167. const updateText = document.getElementById('updateText');
  168. if (currentVersionText) {
  169. currentVersionText.textContent = updateData.current;
  170. }
  171. if (latestVersionText) {
  172. if (updateData.error) {
  173. latestVersionText.textContent = 'Error checking updates';
  174. latestVersionText.className = 'text-red-500 text-sm font-normal leading-normal';
  175. } else {
  176. latestVersionText.textContent = updateData.latest;
  177. latestVersionText.className = 'text-slate-500 text-sm font-normal leading-normal';
  178. }
  179. }
  180. // Update button state
  181. if (updateButton && updateIcon && updateText) {
  182. if (updateData.update_available) {
  183. updateButton.disabled = false;
  184. updateButton.className = 'flex items-center justify-center gap-1.5 min-w-[84px] cursor-pointer rounded-lg h-9 px-3 bg-emerald-500 hover:bg-emerald-600 text-white text-xs font-medium leading-normal tracking-[0.015em] transition-colors';
  185. updateIcon.textContent = 'download';
  186. updateText.textContent = 'Update';
  187. } else {
  188. updateButton.disabled = true;
  189. updateButton.className = 'flex items-center justify-center gap-1.5 min-w-[84px] cursor-pointer rounded-lg h-9 px-3 bg-gray-400 text-white text-xs font-medium leading-normal tracking-[0.015em] transition-colors disabled:opacity-50 disabled:cursor-not-allowed';
  190. updateIcon.textContent = 'check';
  191. updateText.textContent = 'Up to date';
  192. }
  193. }
  194. // Update port selection
  195. const portSelect = document.getElementById('portSelect');
  196. if (portSelect) {
  197. // Clear existing options except the first one
  198. while (portSelect.options.length > 1) {
  199. portSelect.remove(1);
  200. }
  201. // Add new options
  202. ports.forEach(port => {
  203. const option = document.createElement('option');
  204. option.value = port;
  205. option.textContent = port;
  206. portSelect.appendChild(option);
  207. });
  208. // If there's exactly one port available, select it
  209. if (ports.length === 1) {
  210. portSelect.value = ports[0];
  211. }
  212. }
  213. }).catch(error => {
  214. logMessage(`Error initializing settings page: ${error.message}`, LOG_TYPE.ERROR);
  215. });
  216. // Set up event listeners
  217. setupEventListeners();
  218. });
  219. // Setup event listeners
  220. function setupEventListeners() {
  221. // Save/Clear WLED configuration
  222. const saveWledConfig = document.getElementById('saveWledConfig');
  223. const wledIpInput = document.getElementById('wledIpInput');
  224. if (saveWledConfig && wledIpInput) {
  225. saveWledConfig.addEventListener('click', async () => {
  226. if (saveWledConfig.textContent.includes('Clear')) {
  227. // Clear WLED IP
  228. wledIpInput.value = '';
  229. try {
  230. const response = await fetch('/set_wled_ip', {
  231. method: 'POST',
  232. headers: { 'Content-Type': 'application/json' },
  233. body: JSON.stringify({ wled_ip: '' })
  234. });
  235. if (response.ok) {
  236. setWledButtonState(false);
  237. localStorage.removeItem('wled_ip');
  238. showStatusMessage('WLED IP cleared successfully', 'success');
  239. } else {
  240. throw new Error('Failed to clear WLED IP');
  241. }
  242. } catch (error) {
  243. showStatusMessage(`Failed to clear WLED IP: ${error.message}`, 'error');
  244. }
  245. } else {
  246. // Save WLED IP
  247. const wledIp = wledIpInput.value;
  248. try {
  249. const response = await fetch('/set_wled_ip', {
  250. method: 'POST',
  251. headers: { 'Content-Type': 'application/json' },
  252. body: JSON.stringify({ wled_ip: wledIp })
  253. });
  254. if (response.ok && wledIp) {
  255. setWledButtonState(true);
  256. localStorage.setItem('wled_ip', wledIp);
  257. showStatusMessage('WLED IP configured successfully', 'success');
  258. } else {
  259. setWledButtonState(false);
  260. throw new Error('Failed to save WLED configuration');
  261. }
  262. } catch (error) {
  263. showStatusMessage(`Failed to save WLED IP: ${error.message}`, 'error');
  264. }
  265. }
  266. });
  267. }
  268. // Update software
  269. const updateSoftware = document.getElementById('updateSoftware');
  270. if (updateSoftware) {
  271. updateSoftware.addEventListener('click', async () => {
  272. if (updateSoftware.disabled) {
  273. return;
  274. }
  275. try {
  276. const response = await fetch('/api/update', {
  277. method: 'POST'
  278. });
  279. const data = await response.json();
  280. if (data.success) {
  281. showStatusMessage('Software update started successfully', 'success');
  282. } else if (data.manual_update_url) {
  283. // Show modal with manual update instructions, but use wiki link
  284. const wikiData = {
  285. ...data,
  286. manual_update_url: 'https://github.com/tuanchris/dune-weaver/wiki/Updating-software'
  287. };
  288. showUpdateInstructionsModal(wikiData);
  289. } else {
  290. showStatusMessage(data.message || 'No updates available', 'info');
  291. }
  292. } catch (error) {
  293. logMessage(`Error updating software: ${error.message}`, LOG_TYPE.ERROR);
  294. showStatusMessage('Failed to check for updates', 'error');
  295. }
  296. });
  297. }
  298. // Connect button
  299. const connectButton = document.getElementById('connectButton');
  300. if (connectButton) {
  301. connectButton.addEventListener('click', async () => {
  302. const portSelect = document.getElementById('portSelect');
  303. if (!portSelect || !portSelect.value) {
  304. logMessage('Please select a port first', LOG_TYPE.WARNING);
  305. return;
  306. }
  307. try {
  308. const response = await fetch('/connect', {
  309. method: 'POST',
  310. headers: { 'Content-Type': 'application/json' },
  311. body: JSON.stringify({ port: portSelect.value })
  312. });
  313. if (response.ok) {
  314. logMessage('Connected successfully', LOG_TYPE.SUCCESS);
  315. await updateSerialStatus(true); // Force update after connecting
  316. } else {
  317. throw new Error('Failed to connect');
  318. }
  319. } catch (error) {
  320. logMessage(`Error connecting to device: ${error.message}`, LOG_TYPE.ERROR);
  321. }
  322. });
  323. }
  324. // Disconnect button
  325. const disconnectButton = document.getElementById('disconnectButton');
  326. if (disconnectButton) {
  327. disconnectButton.addEventListener('click', async () => {
  328. try {
  329. const response = await fetch('/disconnect', {
  330. method: 'POST'
  331. });
  332. if (response.ok) {
  333. logMessage('Device disconnected successfully', LOG_TYPE.SUCCESS);
  334. await updateSerialStatus(true); // Force update after disconnecting
  335. } else {
  336. throw new Error('Failed to disconnect device');
  337. }
  338. } catch (error) {
  339. logMessage(`Error disconnecting device: ${error.message}`, LOG_TYPE.ERROR);
  340. }
  341. });
  342. }
  343. }
  344. // Button click handlers
  345. document.addEventListener('DOMContentLoaded', function() {
  346. // Home button
  347. const homeButton = document.getElementById('homeButton');
  348. if (homeButton) {
  349. homeButton.addEventListener('click', async () => {
  350. try {
  351. const response = await fetch('/send_home', {
  352. method: 'POST',
  353. headers: {
  354. 'Content-Type': 'application/json'
  355. }
  356. });
  357. const data = await response.json();
  358. if (data.success) {
  359. updateStatus('Moving to home position...');
  360. }
  361. } catch (error) {
  362. console.error('Error sending home command:', error);
  363. updateStatus('Error: Failed to move to home position');
  364. }
  365. });
  366. }
  367. // Stop button
  368. const stopButton = document.getElementById('stopButton');
  369. if (stopButton) {
  370. stopButton.addEventListener('click', async () => {
  371. try {
  372. const response = await fetch('/stop_execution', {
  373. method: 'POST',
  374. headers: {
  375. 'Content-Type': 'application/json'
  376. }
  377. });
  378. const data = await response.json();
  379. if (data.success) {
  380. updateStatus('Execution stopped');
  381. }
  382. } catch (error) {
  383. console.error('Error stopping execution:', error);
  384. updateStatus('Error: Failed to stop execution');
  385. }
  386. });
  387. }
  388. // Move to Center button
  389. const centerButton = document.getElementById('centerButton');
  390. if (centerButton) {
  391. centerButton.addEventListener('click', async () => {
  392. try {
  393. const response = await fetch('/move_to_center', {
  394. method: 'POST',
  395. headers: {
  396. 'Content-Type': 'application/json'
  397. }
  398. });
  399. const data = await response.json();
  400. if (data.success) {
  401. updateStatus('Moving to center position...');
  402. }
  403. } catch (error) {
  404. console.error('Error moving to center:', error);
  405. updateStatus('Error: Failed to move to center');
  406. }
  407. });
  408. }
  409. // Move to Perimeter button
  410. const perimeterButton = document.getElementById('perimeterButton');
  411. if (perimeterButton) {
  412. perimeterButton.addEventListener('click', async () => {
  413. try {
  414. const response = await fetch('/move_to_perimeter', {
  415. method: 'POST',
  416. headers: {
  417. 'Content-Type': 'application/json'
  418. }
  419. });
  420. const data = await response.json();
  421. if (data.success) {
  422. updateStatus('Moving to perimeter position...');
  423. }
  424. } catch (error) {
  425. console.error('Error moving to perimeter:', error);
  426. updateStatus('Error: Failed to move to perimeter');
  427. }
  428. });
  429. }
  430. });
  431. // Function to update status
  432. function updateStatus(message) {
  433. const statusElement = document.querySelector('.text-slate-800.text-base.font-medium.leading-normal');
  434. if (statusElement) {
  435. statusElement.textContent = message;
  436. // Reset status after 3 seconds if it's a temporary message
  437. if (message.includes('Moving') || message.includes('Execution')) {
  438. setTimeout(() => {
  439. statusElement.textContent = 'Status';
  440. }, 3000);
  441. }
  442. }
  443. }
  444. // Function to show status messages (using existing base.js showStatusMessage if available)
  445. function showStatusMessage(message, type) {
  446. if (typeof window.showStatusMessage === 'function') {
  447. window.showStatusMessage(message, type);
  448. } else {
  449. // Fallback to console logging
  450. console.log(`[${type}] ${message}`);
  451. }
  452. }
  453. // Function to show update instructions modal
  454. function showUpdateInstructionsModal(data) {
  455. // Create modal HTML
  456. const modal = document.createElement('div');
  457. modal.id = 'updateInstructionsModal';
  458. modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4';
  459. modal.innerHTML = `
  460. <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md">
  461. <div class="p-6">
  462. <div class="text-center mb-4">
  463. <h2 class="text-xl font-semibold text-gray-800 dark:text-gray-200 mb-2">Manual Update Required</h2>
  464. <p class="text-gray-600 dark:text-gray-400 text-sm">
  465. ${data.message}
  466. </p>
  467. </div>
  468. <div class="text-gray-700 dark:text-gray-300 text-sm mb-6">
  469. <p class="mb-3">${data.instructions}</p>
  470. </div>
  471. <div class="flex gap-3 justify-center">
  472. <button id="openGitHubRelease" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors">
  473. View Update Instructions
  474. </button>
  475. <button id="closeUpdateModal" class="px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg transition-colors">
  476. Close
  477. </button>
  478. </div>
  479. </div>
  480. </div>
  481. `;
  482. document.body.appendChild(modal);
  483. // Add event listeners
  484. const openGitHubButton = modal.querySelector('#openGitHubRelease');
  485. const closeButton = modal.querySelector('#closeUpdateModal');
  486. openGitHubButton.addEventListener('click', () => {
  487. window.open(data.manual_update_url, '_blank');
  488. document.body.removeChild(modal);
  489. });
  490. closeButton.addEventListener('click', () => {
  491. document.body.removeChild(modal);
  492. });
  493. // Close on outside click
  494. modal.addEventListener('click', (e) => {
  495. if (e.target === modal) {
  496. document.body.removeChild(modal);
  497. }
  498. });
  499. }