// wrt + socket + contrl const io = require("socket.io-client") const PWM = require('./lib/Pwm') const { PeerConnection, Video } = require('node-datachannel'); const { createSocket } = require('dgram') const { spawn } = require('child_process') const url = 'ws://10.10.3.196:7896' class CarServer { constructor() { this.Peer = null this.track = null this.child = null this.udp = null this.socket = io(url, { auth: { roomID: "feiCar", name: 'car' } }); this.socket.on('connect', this.connected.bind(this)) this.socket.on('msg', this.onMsg.bind(this)) this.socket.on('leaved', this.onLeved.bind(this)) this.socket.on('joined', this.startVideo.bind(this)) this.socket.on('disconnect',this.onLeved.bind(this)) } // socket 连接 connected() { console.log('connected'); this.Peer = new PeerConnection("Peer1", { iceServers: [] }); // 发送offer this.Peer.onGatheringStateChange(state => { console.log('GatheringState: ', state); if (state === 'complete') { const offer = this.Peer.localDescription(); this.socket.emit("msg", offer); } }) } // 用户信息 onMsg(data) { try { if (data.type == 'answer') { this.Peer.setRemoteDescription(data.sdp, data.type); } else if (data.type === 'startRTC') { this.startVideo() } if (data.type === 'conctrl') { const state = this.Peer.state(); if(state === 'connected') PWM.changPWM(data.conctrl); } } catch (error) { console.log(error); throw error } } // 用户离开 onLeved() { if (this.child) this.child.kill() if (this.udp) this.udp.close() PWM.stop() this.child = null this.udp = null process.exit(1) } // 开始视频 startVideo() { try { if (this.child) this.child.kill() if (this.udp) this.udp.close() // test video const video = new Video('video', 'SendOnly') video.addH264Codec(96) video.addSSRC(42, "video-send") this.track = this.Peer.addTrack(video) this.Peer.setLocalDescription() // UDP server const port = 7788 this.udp = createSocket("udp4") this.udp.bind(port) // video push const args = [ "libcamerasrc", "video/x-raw,width=960,height=720", "videoconvert", "queue", "x264enc tune=zerolatency bitrate=1000 key-int-max=30 speed-preset=1", "video/x-h264, profile=constrained-baseline", "rtph264pay pt=96 mtu=1200 ssrc=42", `udpsink host=127.0.0.1 port=${port}`, ].join(" ! ").split(" ") this.child = spawn("gst-launch-1.0", args) // listen UDP this.udp.on("message", (data) => { if (!this.track.isOpen()) return this.track.sendMessageBinary(data) }); } catch (error) { console.log(error); throw error } } } new CarServer()