4
0

websocket.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. window.ws = null
  2. export function checkWebsocketConnection () {
  3. if (window.ws === null || window.ws.readyState === 3) {
  4. reconnectWebsocket()
  5. }
  6. }
  7. function reconnectWebsocket () {
  8. window.websocketAvailable = false
  9. const websocketConnectionUrl = new URL(window.location.toString())
  10. websocketConnectionUrl.hash = ''
  11. websocketConnectionUrl.pathname += 'websocket'
  12. if (window.location.protocol === 'https:') {
  13. websocketConnectionUrl.protocol = 'wss'
  14. } else {
  15. websocketConnectionUrl.protocol = 'ws'
  16. }
  17. window.websocketConnectionUrl = websocketConnectionUrl
  18. const ws = window.ws = new WebSocket(websocketConnectionUrl.toString())
  19. ws.addEventListener('open', websocketOnOpen)
  20. ws.addEventListener('message', websocketOnMessage)
  21. ws.addEventListener('error', websocketOnError)
  22. ws.addEventListener('close', websocketOnClose)
  23. }
  24. function websocketOnOpen (evt) {
  25. window.websocketAvailable = true
  26. window.ws.send('monitor')
  27. window.refreshLoop()
  28. }
  29. function websocketOnMessage (msg) {
  30. // FIXME check msg status is OK
  31. const j = JSON.parse(msg.data)
  32. const e = new Event(j.type)
  33. e.payload = j.payload
  34. switch (j.type) {
  35. case 'EventConfigChanged':
  36. case 'EventExecutionFinished':
  37. case 'EventEntityChanged':
  38. window.dispatchEvent(e)
  39. break
  40. default:
  41. window.showBigError('ws-unhandled-message', 'handling websocket message', 'Unhandled websocket message type from server: ' + j.type, true)
  42. }
  43. }
  44. function websocketOnError (err) {
  45. window.websocketAvailable = false
  46. window.refreshLoop()
  47. console.error(err)
  48. }
  49. function websocketOnClose () {
  50. window.websocketAvailable = false
  51. }