let _peerConnection = null ; let _dataChannel = null ; export function setPeerConnection ( ) { _peerConnection = new RTCPeerConnection ( { iceServers : [ { urls : 'stun:stun.l.google.com:19302' , } , ] , } ) ; } export function getPeerConnection ( ) { if ( _peerConnection === null ) { throw new Error ( 'Set drone connection before accessing it' ) ; } return _peerConnection ; } export function setStreamCallback ( video ) { const peerConnection = getPeerConnection ( ) ; peerConnection . addTransceiver ( 'video' , { direction : 'recvonly' } ) ; peerConnection . ontrack = event => { video . srcObject = event . streams [ 0 ] ; video . autoplay = true ; } ; } export async function negotiateConnection ( ) { const peerConnection = getPeerConnection ( ) ; const dataChannelIsOpen = setCommandDataChannel ( ) ; const offer = await peerConnection . createOffer ( ) ; peerConnection . setLocalDescription ( offer ) ; const answer = await fetch ( 'http://localhost:50000' , { method : 'POST' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( offer ) , } ) ; const response = await answer . json ( ) ; await peerConnection . setRemoteDescription ( response ) ; await dataChannelIsOpen ; } export function setCommandDataChannel ( ) { const peerConnection = getPeerConnection ( ) ; const initiateDataChannel = peerConnection . createDataChannel ( 'commands' ) ; const isOpen = new Promise ( resolve => { initiateDataChannel . onopen = e => { _dataChannel = initiateDataChannel ; resolve ( ) ; } ; } ) ; return isOpen ; } export function getCommandDataChannel ( ) { if ( _dataChannel === null ) { throw new Error ( 'Set command channel before accessing it' ) ; } return _dataChannel ; } export function sendCommand ( command ) { const dataChannel = getCommandDataChannel ( ) ; dataChannel . send ( command ) ; } export function connectToDrone ( ) { sendCommand ( 'command' ) ; } export function streamOn ( ) { sendCommand ( 'streamon' ) ; } export function streamOff ( ) { sendCommand ( 'streamoff' ) ; } export function takeOff ( ) { sendCommand ( 'takeoff' ) ; } export function land ( ) { sendCommand ( 'land' ) ; } export function down ( distance ) { sendCommand ( `down ${ distance }` ) ; } export function up ( distance ) { sendCommand ( `up ${ distance }` ) ; } export function left ( distance ) { sendCommand ( `left ${ distance }` ) ; } export function right ( distance ) { sendCommand ( `right ${ distance }` ) ; } export function setSpeed ( speed ) { sendCommand ( `speed ${ speed }` ) ; }