monitor.coffee 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. el = (id) -> document.getElementById(id)
  2. set = (id, value) -> el(id).innerHTML = value
  3. values = (e for e in el('content').getElementsByTagName('span')) \
  4. .concat(el('release'))
  5. connect = ->
  6. val.innerHTML = 'Connecting...' for val in values
  7. ws = new WebSocket 'ws://localhost:12345'
  8. ws.onopen = ->
  9. console.log 'open'
  10. el('status').className = 'right online'
  11. set('status', '<i class="icon-off"></i>Online')
  12. ws.onclose = ->
  13. console.log 'close'
  14. val.innerHTML = '-' for val in values
  15. el('status').className = 'right offline'
  16. set('status', '<i class="icon-off"></i>Offline')
  17. setTimeout connect, 5000
  18. ws.onerror = (e) ->
  19. console.log 'error', e
  20. ws.onmessage = (msg) ->
  21. console.log 'msg', msg.data
  22. data = JSON.parse(msg.data)
  23. set('release', data.os) if data.os
  24. set('uptime', fmt_time(data.uptime)) if data.uptime
  25. if data.temps.length
  26. el('temp').innerHTML = ("#{deg}&#8451;" for deg in data.temps) \
  27. .join('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
  28. set('cpu-usage', "#{data.cpu_usage}%") if data.cpu_usage
  29. set('memory', fmt_kbytes_usage(data.memory)) if data.memory
  30. set('disk', fmt_kbytes_usage(data.disk)) if data.disk
  31. fmt_time = (total) ->
  32. total = Math.round total
  33. s = (n) -> if n == 1 then '' else 's'
  34. secs = total % 60
  35. str = "#{secs} second" + s(secs)
  36. if total >= 60
  37. mins = parseInt total % (60 * 60) / 60
  38. str = "#{mins} minute#{s(mins)}, #{str}"
  39. if total >= 60 * 60
  40. hours = parseInt total % (60 * 60 * 24) / (60 * 60)
  41. str = "#{hours} hour#{s(hours)}, #{str}"
  42. str
  43. fmt_kbytes_usage = ([used, total]) ->
  44. used = Math.round used / 1000
  45. total = Math.round total / 1000
  46. perc = Math.round used / total * 100
  47. return "#{used}MB / #{total}MB (#{perc}%)"
  48. connect()