settings.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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('/check_software_update').then(response => response.json()).catch(() => ({ current_version: '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. document.querySelector('.text-slate-500.text-sm.font-normal.leading-normal').textContent = updateData.current_version;
  164. // Show/hide update button
  165. const updateButton = document.getElementById('updateSoftware');
  166. if (updateButton) {
  167. updateButton.style.display = updateData.update_available ? 'flex' : 'none';
  168. }
  169. // Update port selection
  170. const portSelect = document.getElementById('portSelect');
  171. if (portSelect) {
  172. // Clear existing options except the first one
  173. while (portSelect.options.length > 1) {
  174. portSelect.remove(1);
  175. }
  176. // Add new options
  177. ports.forEach(port => {
  178. const option = document.createElement('option');
  179. option.value = port;
  180. option.textContent = port;
  181. portSelect.appendChild(option);
  182. });
  183. // If there's exactly one port available, select it
  184. if (ports.length === 1) {
  185. portSelect.value = ports[0];
  186. }
  187. }
  188. }).catch(error => {
  189. logMessage(`Error initializing settings page: ${error.message}`, LOG_TYPE.ERROR);
  190. });
  191. // Set up event listeners
  192. setupEventListeners();
  193. });
  194. // Setup event listeners
  195. function setupEventListeners() {
  196. // Save/Clear WLED configuration
  197. const saveWledConfig = document.getElementById('saveWledConfig');
  198. const wledIpInput = document.getElementById('wledIpInput');
  199. if (saveWledConfig && wledIpInput) {
  200. saveWledConfig.addEventListener('click', async () => {
  201. if (saveWledConfig.textContent.includes('Clear')) {
  202. // Clear WLED IP
  203. wledIpInput.value = '';
  204. try {
  205. const response = await fetch('/set_wled_ip', {
  206. method: 'POST',
  207. headers: { 'Content-Type': 'application/json' },
  208. body: JSON.stringify({ wled_ip: '' })
  209. });
  210. if (response.ok) {
  211. setWledButtonState(false);
  212. localStorage.removeItem('wled_ip');
  213. showStatusMessage('WLED IP cleared successfully', 'success');
  214. } else {
  215. throw new Error('Failed to clear WLED IP');
  216. }
  217. } catch (error) {
  218. showStatusMessage(`Failed to clear WLED IP: ${error.message}`, 'error');
  219. }
  220. } else {
  221. // Save WLED IP
  222. const wledIp = wledIpInput.value;
  223. try {
  224. const response = await fetch('/set_wled_ip', {
  225. method: 'POST',
  226. headers: { 'Content-Type': 'application/json' },
  227. body: JSON.stringify({ wled_ip: wledIp })
  228. });
  229. if (response.ok && wledIp) {
  230. setWledButtonState(true);
  231. localStorage.setItem('wled_ip', wledIp);
  232. showStatusMessage('WLED IP configured successfully', 'success');
  233. } else {
  234. setWledButtonState(false);
  235. throw new Error('Failed to save WLED configuration');
  236. }
  237. } catch (error) {
  238. showStatusMessage(`Failed to save WLED IP: ${error.message}`, 'error');
  239. }
  240. }
  241. });
  242. }
  243. // Update software
  244. const updateSoftware = document.getElementById('updateSoftware');
  245. if (updateSoftware) {
  246. updateSoftware.addEventListener('click', async () => {
  247. try {
  248. const response = await fetch('/update_software', {
  249. method: 'POST'
  250. });
  251. if (response.ok) {
  252. logMessage('Software update started successfully', LOG_TYPE.SUCCESS);
  253. } else {
  254. throw new Error('Failed to start software update');
  255. }
  256. } catch (error) {
  257. logMessage(`Error updating software: ${error.message}`, LOG_TYPE.ERROR);
  258. }
  259. });
  260. }
  261. // Connect button
  262. const connectButton = document.getElementById('connectButton');
  263. if (connectButton) {
  264. connectButton.addEventListener('click', async () => {
  265. const portSelect = document.getElementById('portSelect');
  266. if (!portSelect || !portSelect.value) {
  267. logMessage('Please select a port first', LOG_TYPE.WARNING);
  268. return;
  269. }
  270. try {
  271. const response = await fetch('/connect', {
  272. method: 'POST',
  273. headers: { 'Content-Type': 'application/json' },
  274. body: JSON.stringify({ port: portSelect.value })
  275. });
  276. if (response.ok) {
  277. logMessage('Connected successfully', LOG_TYPE.SUCCESS);
  278. await updateSerialStatus(true); // Force update after connecting
  279. } else {
  280. throw new Error('Failed to connect');
  281. }
  282. } catch (error) {
  283. logMessage(`Error connecting to device: ${error.message}`, LOG_TYPE.ERROR);
  284. }
  285. });
  286. }
  287. // Disconnect button
  288. const disconnectButton = document.getElementById('disconnectButton');
  289. if (disconnectButton) {
  290. disconnectButton.addEventListener('click', async () => {
  291. try {
  292. const response = await fetch('/disconnect', {
  293. method: 'POST'
  294. });
  295. if (response.ok) {
  296. logMessage('Device disconnected successfully', LOG_TYPE.SUCCESS);
  297. await updateSerialStatus(true); // Force update after disconnecting
  298. } else {
  299. throw new Error('Failed to disconnect device');
  300. }
  301. } catch (error) {
  302. logMessage(`Error disconnecting device: ${error.message}`, LOG_TYPE.ERROR);
  303. }
  304. });
  305. }
  306. }
  307. // Button click handlers
  308. document.addEventListener('DOMContentLoaded', function() {
  309. // Home button
  310. const homeButton = document.getElementById('homeButton');
  311. homeButton.addEventListener('click', async () => {
  312. try {
  313. const response = await fetch('/send_home', {
  314. method: 'POST',
  315. headers: {
  316. 'Content-Type': 'application/json'
  317. }
  318. });
  319. const data = await response.json();
  320. if (data.success) {
  321. updateStatus('Moving to home position...');
  322. }
  323. } catch (error) {
  324. console.error('Error sending home command:', error);
  325. updateStatus('Error: Failed to move to home position');
  326. }
  327. });
  328. // Stop button
  329. const stopButton = document.getElementById('stopButton');
  330. stopButton.addEventListener('click', async () => {
  331. try {
  332. const response = await fetch('/stop_execution', {
  333. method: 'POST',
  334. headers: {
  335. 'Content-Type': 'application/json'
  336. }
  337. });
  338. const data = await response.json();
  339. if (data.success) {
  340. updateStatus('Execution stopped');
  341. }
  342. } catch (error) {
  343. console.error('Error stopping execution:', error);
  344. updateStatus('Error: Failed to stop execution');
  345. }
  346. });
  347. // Move to Center button
  348. const centerButton = document.getElementById('centerButton');
  349. centerButton.addEventListener('click', async () => {
  350. try {
  351. const response = await fetch('/move_to_center', {
  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 center position...');
  360. }
  361. } catch (error) {
  362. console.error('Error moving to center:', error);
  363. updateStatus('Error: Failed to move to center');
  364. }
  365. });
  366. // Move to Perimeter button
  367. const perimeterButton = document.getElementById('perimeterButton');
  368. perimeterButton.addEventListener('click', async () => {
  369. try {
  370. const response = await fetch('/move_to_perimeter', {
  371. method: 'POST',
  372. headers: {
  373. 'Content-Type': 'application/json'
  374. }
  375. });
  376. const data = await response.json();
  377. if (data.success) {
  378. updateStatus('Moving to perimeter position...');
  379. }
  380. } catch (error) {
  381. console.error('Error moving to perimeter:', error);
  382. updateStatus('Error: Failed to move to perimeter');
  383. }
  384. });
  385. });
  386. // Function to update status
  387. function updateStatus(message) {
  388. const statusElement = document.querySelector('.text-slate-800.text-base.font-medium.leading-normal');
  389. if (statusElement) {
  390. statusElement.textContent = message;
  391. // Reset status after 3 seconds if it's a temporary message
  392. if (message.includes('Moving') || message.includes('Execution')) {
  393. setTimeout(() => {
  394. statusElement.textContent = 'Status';
  395. }, 3000);
  396. }
  397. }
  398. }