networkstatus.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // SPDX-FileCopyrightText: 2012-2023 MOD Audio UG
  2. // SPDX-License-Identifier: AGPL-3.0-or-later
  3. function NetworkStatus(options) {
  4. var self = this
  5. options = $.extend({
  6. icon: $('<div>'),
  7. frequency: 5000,
  8. notify: function (msg) {
  9. console.log(msg)
  10. },
  11. }, options)
  12. var icon = options.icon
  13. var frequency = options.frequency
  14. this.timedOutPhase = 0
  15. this.ping = function () {
  16. if (pb_loading) {
  17. setTimeout(self.ping, frequency)
  18. return
  19. }
  20. var start = Date.now()
  21. $.ajax({
  22. url: '/ping',
  23. cache: false,
  24. global: false,
  25. success: function (resp) {
  26. if (self.timedOutPhase >= 2) {
  27. location.reload()
  28. return
  29. } else {
  30. self.timedOutPhase = 0
  31. }
  32. if (icon.is(':visible')) {
  33. var time = Date.now() - start - resp.ihm_time
  34. self.status(true, time, resp.ihm_time)
  35. }
  36. setTimeout(self.ping, frequency)
  37. },
  38. error: function (resp, error) {
  39. if (resp.status == 0)
  40. {
  41. var loading = $('.screen-loading').is(':visible')
  42. if (document.readyState != "complete" || $.active != 0 || loading || isInstallingPackage)
  43. {
  44. self.timedOutPhase = 0
  45. }
  46. else
  47. {
  48. if (error == "timeout") {
  49. switch (self.timedOutPhase) {
  50. case 1:
  51. desktop.blockUI()
  52. // fall-through
  53. case 0:
  54. console.log("Connection timed out")
  55. self.timedOutPhase++;
  56. break;
  57. }
  58. } else if (error == "error") {
  59. self.timedOutPhase = 3
  60. }
  61. }
  62. }
  63. self.status(false)
  64. setTimeout(self.ping, frequency)
  65. },
  66. dataType: 'json',
  67. timeout: frequency,
  68. })
  69. }
  70. this.status = function (online, network_time, ihm_time) {
  71. var msg
  72. if (online) {
  73. if (ihm_time == 0) {
  74. msg = sprintf('Network: %dms', network_time)
  75. } else {
  76. msg = sprintf('Network: %dms | Controller: %dms', network_time, ihm_time)
  77. }
  78. } else {
  79. msg = 'OFFLINE'
  80. }
  81. options.notify(msg)
  82. }
  83. this.ping()
  84. }