index-test.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // 站点工况(websocket实时推送)
  2. var arrData = [];
  3. var wsUri = "wss://iot.usky.cn:55120";
  4. var websocket;
  5. function initWebSocket() {
  6. return new Promise((res, rej) => {
  7. try {
  8. if (typeof MozWebSocket == 'function')
  9. WebSocket = MozWebSocket;
  10. websocket = new WebSocket(wsUri);
  11. websocket.onopen = function(evt) {
  12. var json = {};
  13. json.agentid = 'admin';
  14. console.log("Connected.");
  15. (function() {})()
  16. console.log('websocket')
  17. console.log(websocket)
  18. websocket.send(JSON.stringify(json));
  19. };
  20. websocket.onclose = function(evt) {
  21. console.log("DisConnected.");
  22. (function() {})()
  23. // initWebSocket();
  24. console.log(1111111)
  25. };
  26. websocket.onmessage = function(evt) {
  27. var siteData = eval('(' + evt.data + ')');
  28. console.log('siteData')
  29. console.log(siteData)
  30. // console.log('arrData')
  31. // console.log(arrData)
  32. //返回值渲染
  33. if (siteData.time) {
  34. $('.receive-time').text('[' + siteData.time + ' 收到]')
  35. $(".receive-request").text(JSON.stringify(siteData, null, 2));
  36. }
  37. };
  38. websocket.onerror = function(evt) {
  39. console.log("Error:", evt.data);
  40. (function() {})()
  41. };
  42. res()
  43. } catch (exception) {
  44. console.log("Exception:", exception);
  45. rej()
  46. }
  47. })
  48. }
  49. //打开websocket
  50. // $('.openWebsocket').on('click', function() {
  51. // initWebSocket();
  52. // })
  53. // initWebSocket()
  54. function isWs(val) {
  55. if (!websocket) {
  56. initWebSocket().then(() => { isWs(val) })
  57. } else if (websocket.readyState == 1) {
  58. websocket.send(val)
  59. } else {
  60. setTimeout(() => {
  61. isWs(val)
  62. }, 1000)
  63. }
  64. }
  65. //站点工况点击
  66. $('.siteCondition').on('click', function() {
  67. var stationId = $('#stationId').val()
  68. var stationName = $('#stationName').val()
  69. var json = {};
  70. json.CMD = 'getStationInfo';
  71. json.StationID = stationId;
  72. json.StationName = stationName;
  73. //发送时间和请求参数页面渲染
  74. time('.send-time');
  75. $(".send-request").text(JSON.stringify(json, null, 2));
  76. if (websocket) {
  77. websocket.close();
  78. websocket = '';
  79. }
  80. isWs(JSON.stringify(json))
  81. })