app.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // webSocket
  2. const WsType = { Weather: 0, System: 1 };
  3. const wsUrl = (window.location.origin.replace("http", "ws") )+ "/ws";
  4. let timeOut = 1;
  5. connect();
  6. // weather elements
  7. const weatherIcon = document.getElementById("weatherIcon");
  8. const weatherTemp = document.getElementById("weatherTemp");
  9. const weatherDescription = document.getElementById("weatherDescription");
  10. const weatherHumidity = document.getElementById("weatherHumidity");
  11. const weatherSunrise = document.getElementById("weatherSunrise");
  12. const weatherSunset = document.getElementById("weatherSunset");
  13. // system elements
  14. const systemCpuPercentage = document.getElementById("systemCpuPercentage");
  15. const systemRamPercentage = document.getElementById("systemRamPercentage");
  16. const systemRamValue = document.getElementById("systemRamValue");
  17. const systemDiskPercentage = document.getElementById("systemDiskPercentage");
  18. const systemDiskValue = document.getElementById("systemDiskValue");
  19. function connect() {
  20. let ws = new WebSocket(wsUrl);
  21. ws.onopen = () => {
  22. console.log("WebSocket is open.");
  23. timeOut = 1;
  24. };
  25. ws.onmessage = (event) => handleMessage(JSON.parse(event.data));
  26. ws.onerror = () => ws.close();
  27. ws.onclose = () => {
  28. console.log("WebSocket is closed. Reconnect will be attempted in " + timeOut + " second.");
  29. setTimeout(() => connect(), timeOut * 1000);
  30. timeOut += 1;
  31. };
  32. }
  33. function handleMessage(parsed) {
  34. if (parsed.ws_type === WsType.Weather) replaceWeather(parsed.message);
  35. else if (parsed.ws_type === WsType.System) replaceSystem(parsed.message);
  36. }
  37. function replaceWeather(parsed) {
  38. weatherIcon.setAttribute("xlink:href", "#" + parsed.icon);
  39. weatherTemp.innerText = parsed.temp;
  40. weatherDescription.innerText = parsed.description;
  41. weatherHumidity.innerText = parsed.humidity;
  42. weatherSunrise.innerText = parsed.sunrise;
  43. weatherSunset.innerText = parsed.sunset;
  44. }
  45. function replaceSystem(parsed) {
  46. systemCpuPercentage.style = "width:" + parsed.cpu + "%";
  47. systemRamPercentage.style = "width:" + parsed.ram.percentage + "%";
  48. systemRamValue.innerText = parsed.ram.value;
  49. systemDiskPercentage.style = "width:" + parsed.disk.percentage + "%";
  50. systemDiskValue.innerText = parsed.disk.value;
  51. }