zhangzengfei
2021-02-01 ecc7498c074243640046ea5f1516949892c1b4a4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
 * Websocket Loader
 */
/* eslint-disable */
import Event from '../events'
import EventHandler from '../event-handler'
import SlicesReader from '../utils/h264-nal-slicesreader.js'
 
class WebsocketLoader extends EventHandler {
  constructor(wfs) {
    super(
      wfs,
      Event.WEBSOCKET_ATTACHING,
      Event.WEBSOCKET_DATA_UPLOADING,
      Event.WEBSOCKET_MESSAGE_SENDING
    )
    this.buf = null
    this.slicesReader = new SlicesReader(wfs)
    this.mediaType = undefined
    this.channelName = undefined
    this.cameraInfo = {}
  }
 
  destroy() {
    !!this.client && this.client.close()
    this.slicesReader.destroy()
    EventHandler.prototype.destroy.call(this)
  }
 
  onWebsocketAttaching(data) {
    this.mediaType = data.mediaType
    this.channelName = data.channelName
    this.cameraInfo = data.cameraInfo
    if (data.websocket instanceof WebSocket) {
      this.client = data.websocket
      this.client.onopen = this.initSocketClient.bind(this)
      this.client.onclose = function (e) {
        console.log('Websocket Disconnected!')
        this.disconnected = true;
        // console.log(this)
        // this.close = true;
        // this.wfs.attachMedia(this.media, "chX", "H264Raw", this.client.url, this.cameraInfo);
      }
    }
  }
 
  initSocketClient(client) {
    this.client.binaryType = 'arraybuffer'
    this.client.onmessage = this.receiveSocketMessage.bind(this)
    this.wfs.trigger(Event.WEBSOCKET_MESSAGE_SENDING, {
      commandType: 'open',
      channelName: this.channelName,
      commandValue: 'NA',
      cameraInfo: this.cameraInfo
    })
    this.client.disconnected = false
    // console.log(this)
    console.log('Websocket Open!')
  }
 
  receiveSocketMessage(event) {
    this.buf = new Uint8Array(event.data)
    var copy = new Uint8Array(this.buf)
 
    if (this.mediaType === 'FMp4') {
      this.wfs.trigger(Event.WEBSOCKET_ATTACHED, { payload: copy })
    }
    if (this.mediaType === 'H264Raw') {
      this.wfs.trigger(Event.H264_DATA_PARSING, { data: copy })
    }
  }
 
  onWebsocketDataUploading(event) {
    this.client.send(event.data)
  }
 
  onWebsocketMessageSending(event) {
    this.client.send(
      JSON.stringify({
        cameraID: event.cameraInfo.cameraID,
        rtspUrl: event.cameraInfo.rtspUrl,
        isRunning: event.cameraInfo.isRunning,
        isGb28181: event.cameraInfo.isGb28181
      })
    )
  }
}
 
export default WebsocketLoader