This repository was archived by the owner on Jul 17, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfirebaseRTC_client2.html
220 lines (199 loc) · 7.25 KB
/
firebaseRTC_client2.html
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<!-- <video id="myVideo" autoplay muted playsinline></video> -->
<video id="piVideo" autoplay muted playsinline></video>
<!-- <button onclick="connectToPi()" type="button">Call</button> -->
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.1.0/firebase-app.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/7.1.0/firebase-analytics.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.1.0/firebase-firestore.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyC2AMehEW9xsxtLdVKHzZG7ENNh2wrBNw0",
authDomain: "mspi-a4b75.firebaseapp.com",
databaseURL: "https://mspi-a4b75.firebaseio.com",
projectId: "mspi-a4b75",
storageBucket: "mspi-a4b75.appspot.com",
messagingSenderId: "224698699586",
appId: "1:224698699586:web:33bb9a289a097f74a302db",
measurementId: "G-RBB4FBV72Q"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
var db = firebase.firestore();
var servers = {
iceServers: [
{
urls: "stun:stun.services.mozilla.com"
},
{
urls: "stun:stun.l.google.com:19302"
},
{
urls: "turn:numb.viagenie.ca",
credential: "charlietheunicorn",
username: "[email protected]"
}
]
};
var pc = new RTCPeerConnection(servers);
const dbCollection = "webrtctest";
var myVideo = document.getElementById("myVideo");
var piVideo = document.getElementById("piVideo");
var myId = "PiTest";
var piId = "MyId";
let hasLocalDesc = false;
let hasRemoteDesc = false;
//Send local ice candidates
pc.onicecandidate = event =>
event.candidate
? sendMessage("iceCandidate", event.candidate)
: console.log("Sent All Ice");
//If WebRTC detects a stream added on other side, set video to that stream
pc.onaddstream = event => (piVideo.srcObject = event.stream);
pc.oniceconnectionstatechange = function() {
if(pc.iceConnectionState == 'disconnected') {
hasLocalDesc = false;
hasRemoteDesc = false;
piVideo.srcObject = null;
console.log('Disconnected');
}
}
function hasUserMedia() {
//check if the browser supports the WebRTC
return !!(
navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia
);
}
if (hasUserMedia()) {
navigator.getUserMedia =
navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia;
//enabling video and audio channels
navigator.getUserMedia(
{
video: true,
audio: true
},
function(stream) {
//myVideo.srcObject = stream;
// pc.addStream(stream);
},
function(err) {}
);
} else {
alert("WebRTC is not supported");
}
// //Query database collection
// db.collection(dbCollection).get().then((querySnapshot) => {
// querySnapshot.forEach((doc) => {
// console.log(`${doc.id} => ${doc.data()}`);
// });
// });
function sendMessage(type, data, options = {}) {
let d = JSON.stringify(data);
db.collection(dbCollection).add({
sender: myId,
what: type,
data: d,
options: options
});
}
async function connectToPi() {
if (!hasLocalDesc) {
await pc
.createOffer()
.then(offer => pc.setLocalDescription(offer))
.then(() => sendMessage("offer", pc.localDescription));
console.log("Sent offer:" + pc.localDescription);
hasLocalDesc = true;
}
}
function convertToRTCSessionDescriptionInit(data) {
let cache = {
type: data.type,
sdp: data.sdp
};
return cache;
}
function listenIce() {
db.collection(dbCollection)
.where("sender", "==", piId)
.onSnapshot(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
let type = doc.data().what;
let data = JSON.parse(doc.data().data);
console.log(data);
if (type == "iceCandidate") {
//iceCandidates allow NAT Traversal so the PCs can find each other
pc.addIceCandidate(new RTCIceCandidate(data));
deleteRecord(doc.id);
console.log("Recieved Ice");
}
//console.log(`${doc.id} => ${doc.data().what}`);
});
});
}
function deleteRecord(id) {
//Delete signal so we don't process it again
db.collection(dbCollection)
.doc(id)
.delete()
.then(function() {
console.log("Document successfully deleted!");
})
.catch(function(error) {
console.error("Error removing document: ", error);
});
}
//Attaches listener to listen for signal from Raspberry Pi
//Runs function every time it detects a change
db.collection(dbCollection)
.where("sender", "==", piId)
.onSnapshot(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
let type = doc.data().what;
let data = JSON.parse(doc.data().data);
//console.log(data);
if (type == "offer" && !hasLocalDesc && !hasRemoteDesc) {
data.type = type;
data = convertToRTCSessionDescriptionInit(data);
console.log(data);
//If recieving an offer, set it as remote "address" for WebRTC and send an answer
pc.setRemoteDescription(new RTCSessionDescription(data))
.then(() => pc.createAnswer())
//Set local "address" as the answer we just created
.then(answer => pc.setLocalDescription(answer))
.then(() => sendMessage("answer", pc.localDescription));
deleteRecord(doc.id);
hasLocalDesc = true;
hasRemoteDesc = true;
console.log("Recieved offer, sent answer");
listenIce();
} else if (type == "answer" && !hasRemoteDesc) {
data.type = type;
data = convertToRTCSessionDescriptionInit(data);
//If recieving an answer, set it as remote "address" for WebRTC
pc.setRemoteDescription(new RTCSessionDescription(data));
deleteRecord(doc.id);
hasRemoteDesc = true;
console.log("Recieved answer");
listenIce();
}
//console.log(`${doc.id} => ${doc.data().what}`);
});
});
</script>
</body>
</html>