websocket.js 1.9 KB

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