I'm not getting any kind of transfer to happen between my chrome app and a simple device just waiting for data to come in on its uart rx line. The device's interface's endpoint's type is bulk, although I've tried every transfer type available (control, bulk, isochronous, and interrupt). Examples from here. I've also tried claiming the device, but that does not seem to be applicable if using findDevices and fails as well.
I'm assuming that by finding the device, I know that it has been discovered, permissions are OK and that it has been opened OK.
I'm using a UART-to-USB adapter on a mac. I've spoken to the same hardware setup using pysusb and a python script, so I know it can be done.
var DEVICE_INFO = {"vendorId": 1027, "productId": 24577};
var searchForUsbDevice = function() {
chrome.usb.findDevices(DEVICE_INFO, onDeviceFound);
}
var onDeviceFound = function(devices) {
if (devices) {
if (0 < devices.length) {
if (1 === devices.length) {
device_ = devices[0];
console.log("Device found. And opened?");
getInterfaces();
getConfiguration();
//claimDevice();
investigateDevice();
} else {
console.log("Ensure one and ONLY ONE device is plugged in.");
}
} else {
console.log("Device could not be found");
setTimeout(searchForUsbDevice, 1000);
}
} else {
console.log("Permission denied.");
}
};
var investigateDevice = function() {
testBulkTransfer();
//testIsochronousTransfer();
//testInterruptTransfer();
//testControlTransfer();
setTimeout(investigateDevice, 1000);
};
var testBulkTransfer = function() {
var transferInfo = {
"direction": "out",
"endpoint": 1,
"data": new Uint8Array([32, 2, 1, 2]).buffer
};
chrome.usb.bulkTransfer(device_, transferInfo, function(info) {
if (chrome.runtime.lastError) {
console.log("info: " + JSON.stringify(info));
console.log("runtime error: " + JSON.stringify(chrome.runtime.lastError.message));
return;
}
console.log("transfer result: " + ((0 === info.resultCode) ? "succeeded" : "failed"));
});
};
var getConfiguration = function() {
chrome.usb.getConfiguration(device_, function(config) {
if (chrome.runtime.lastError) {
console.log("runtime error: " + JSON.stringify(chrome.runtime.lastError.message));
return;
}
console.log("config: ");
console.log(config);
});
};
var getInterfaces = function() {
chrome.usb.listInterfaces(device_, function(descriptors) {
if (chrome.runtime.lastError) {
console.log("runtime error: " + JSON.stringify(chrome.runtime.lastError.message));
return;
}
console.log("descriptors: ");
console.log(descriptors);
});
};
The appropriate API for that UART-to-USB adapter is chrome.serial, NOT chrome.usb.
https://developer.chrome.com/apps/app_serial
Related
The goal is to have a webrtc video/audio p2p connection.
I did take some examples and put them together and manage to get far enough that "most" exchange (via eventsource on NodeJS) is done, just remote stream is not received.
I found that Chrome browser had a bug in which the request is send twice (any fix for this?).
But even when I use firefox (on laptop and phone), there is just no stream received.
with no error on both sides.
This is the full script:
if (!console || !console.log) {
var console = {
log: function() {}
};
}
// Ugh, globals.
// const signaling = new SignalingChannel(); hier moet een module voor komen, als een EventServerSide en/of Websocket...
var peerc;
var source = new EventSource("events");
var selfView = document.getElementById('localvideo');
var remoteView = document.getElementById('remotevideo');
//var TextHistory = ["apple", "orange", "cherry"]; //[ ];
var audio = null;
var audioSendTrack = null;
var video = null;
var videoSendTrack = null;
var chatbox = document.getElementById("chatbox");
var constraints = {video:true, audio:true};
var configuration = {
iceServers: [{
'urls': 'stun:stun.l.google.com:19302'
}]
};
var started = false;
var pc;
$("#incomingCall").modal();
$("#incomingCall").modal("hide");
$("#incomingCall").on("hidden", function() {
document.getElementById("incomingRing").pause();
});
source.addEventListener("ping", function(e) {}, false);
source.addEventListener("userjoined", function(e) {
appendUser(e.data);
}, false);
source.addEventListener("userleft", function(e) {
removeUser(e.data);
}, false);
source.addEventListener("offer", async function(e) {
log("offer received");
if (!pc) {
log("PeerConnection ontbreekt");
warmup(false);
} else {
warmup(true);
}
try {
const message = JSON.parse(e.data);
if (message.desc) {
log("Offer: Desc");
const desc = message.desc;
// if we get an offer, we need to reply with an answer
if (desc.type == 'offer') {
log("Offer: Desc offer");
var connectionState = pc.connectionState;
log(connectionState);
await pc.setRemoteDescription(JSON.parse(desc)); // Parse nodig?
await pc.setLocalDescription(await pc.createAnswer());
var connectionState = pc.connectionState;
log(connectionState);
//signaling.send(JSON.stringify({desc: pc.localDescription}));
jQuery.post(
"offer", {
to: message.from,
from: document.getElementById("user").innerHTML,
desc: JSON.stringify(pc.localDescription)
},
function() { log("Offer sent!"); }
).error("desc", error);
} else {
log("Offer: Desc answer");
await pc.setRemoteDescription(JSON.parse(desc));
}
} else if (message.start) {
log("Offer: Start received from: " + message.from);
started = true;
voor = message.from
van = message.to
if (audio && audioSendTrack) {
log("Wacht op audio");
await audio.sender.replaceTrack(audioSendTrack);
}
if (video && videoSendTrack) {
log("Wacht op video");
await video.sender.replaceTrack(videoSendTrack);
}
log("Offer: Started....wat next???");
} else {
log("Offer: wacht op candidate");
log(message.candidate);
await pc.addIceCandidate(message.candidate);
}
} catch (err) {
console.log(err);
log("Error in Offer event: " + err);
}
}, false);
source.addEventListener("message", function(e) {
var message = JSON.parse(e.data);
text = "User: " + message.from + " - Say: " + message.text;
WriteChat(text);
}, false);
source.addEventListener("answer", function(e) {
var answer = JSON.parse(e.data);
peerc.setRemoteDescription(new RTCSessionDescription(JSON.parse(answer.answer)), function() {
console.log("Call established!");
}, error);
}, false);
function log(info) {
var d = document.getElementById("debug");
d.innerHTML += info + "\n\n";
}
function appendUser(user) {
// If user already exists, ignore it
var index = users.indexOf(user);
if (index > -1)
return;
users.push(user);
console.log("appendUser: user = " + user + ", users.length = " + users.length);
var d = document.createElement("div");
d.setAttribute("id", btoa(user));
var a = document.createElement("button");
a.setAttribute("class", "vertical-align");
a.setAttribute("onclick", "initiateCall('" + user + "');"); //Dit moet dus prive chat worden.
a.innerHTML = "<i class='icon-user icon-white'></i> " + user;
d.appendChild(a);
d.appendChild(document.createElement("br"));
document.getElementById("users").appendChild(d);
}
function removeUser(user) {
// If user already exists, ignore it
var index = users.indexOf(user);
if (index == -1)
return;
users.splice(index, 1)
var d = document.getElementById(btoa(user));
if (d) {
document.getElementById("users").removeChild(d);
}
}
function sendPrive(user) {
log("Prive message"); // + JSON.stringify(offer));
if(!user) { user = "niets!"};
jQuery.post(
"message", {
to: user,
from: document.getElementById("user").innerHTML,
text: JSON.stringify(message)
},
function() { console.log("Message sent!"); }
).error("privemsg",error);
}
function offer(data){
log("Offer to send message: " + JSON.stringify(data));
// start
// desc + type
// candidate
jQuery.post(
"offer", {data: JSON.stringify(data)},
function() { console.log("Message sent!"); }
).error("offer",error);
}
function BroadcastMessage() {
log("Broadcast Message"); // + JSON.stringify(offer)); //function uitbreiden met argumentinvoer
message = document.getElementById("text_input").value;
jQuery.post(
"message", {
to: user,
from: document.getElementById("user").innerHTML,
text: JSON.stringify(message)
},
function() { console.log("Message sent!"); }
).error("BroadcastMessage",error);
//WriteChat(msg);
}
// Dit is een interne, dit moet dus via events gaan!!
function WriteChat(text){
// kan nog user en tijd bijkomen...
chatbox.innerHTML += text + "<br>"; // deze werkt dus niet meer, canvas wil andere methode
}
// Call warmup() to warm-up ICE, DTLS, and media, but not send media yet.
async function warmup(isAnswerer) {
log("Warming up...");
pc = new RTCPeerConnection(configuration);
if (!isAnswerer) { //uitzoeken waarom deze uitgeschakelen...
audio = pc.addTransceiver('audio');
video = pc.addTransceiver('video');
}
// send any ice candidates to the other peer
pc.onicecandidate = (event) => {
log("Offer: onicecandidate...");
//signaling.send(JSON.stringify({candidate: event.candidate}));
log(event.candidate)
if(event.candidate){
jQuery.post(
"offer", {
to: voor,
from: document.getElementById("user").innerHTML,
data: event.candidate, // debugging...
candidate: event.candidate
}, // hier zijn we nu...candidate blijft leeg????
function() { log("Offer: onicecandidate sent!"); }
).error("onicecandidate",error);
} else {
log("geen candidate");
}
};
pc.onnegotiationneeded = function() {
log("negotiation nodig...");
//var connectionState = RTCPeerConnection.connectionState;
pc.createOffer().then(function(aanbod) {
var connectionState = pc.connectionState;
log(connectionState);
log(JSON.stringify(aanbod));
return pc.setLocalDescription(aanbod);
})
.then(function() {
log(JSON.stringify(pc.localDescription));
jQuery.post(
"offer", {
to: document.getElementById("user").innerHTML,
from: voor,
desc: JSON.stringify(pc.localDescription)
},
function() { log("Offer: localDescription sent!"); }
).error("onnegotiationneeded",error);
})
.catch(error);
}
log("Remote video");
// once media for the remote track arrives, show it in the remote video element
pc.ontrack = async (event) => {
log("start ontrack...");
remoteView.srcObject = event.streams[0];
remoteView.play();
selfView.play();
log("oude ontrack...");
try {
log(event.track.kind);
if (event.track.kind == 'audio') {
log("Track heeft audio");
if (isAnswerer) {
log("beantwoord audio");
audio = event.transceiver;
audio.direction = 'sendrecv';
if (started && audioSendTrack) {
await audio.sender.replaceTrack(audioSendTrack);
}
}
}
} catch (err) {
console.log(err);
log("Error in audio ontrack: " + err);
}
try {
log(event.track.kind);
if (event.track.kind == 'video') {
log("Track heeft video");
if (isAnswerer) {
log("beantwoord video");
video = event.transceiver;
video.direction = 'sendrecv';
if (started && videoSendTrack) {
await video.sender.replaceTrack(videoSendTrack);
}
}
}
} catch (err) {
console.log(err);
log("Error in video ontrack: " + err);
}
try {
// don't set srcObject again if it is already set.
if (!remoteView.srcObject) {
log("Nog geen remote video...");
remoteView.srcObject = new MediaStream();
}
log("Voeg remote video toe...");
log(event.track);
remoteView.srcObject.addTrack(event.track);
} catch (err) {
console.log(err);
log("Error in last ontrack: " + err);
}
};
log("Local video & audio");
try {
// get a local stream, show it in a self-view and add it to be sent
const stream = await navigator.mediaDevices.getUserMedia(constraints);
selfView.srcObject = stream;
audioSendTrack = stream.getAudioTracks()[0];
if (started) {
log("Started = True => audio");
log(audio)
await audio.sender.replaceTrack(audioSendTrack);
}
videoSendTrack = stream.getVideoTracks()[0];
if (started) {
log("Started = True => video");
log(video)
await video.sender.replaceTrack(videoSendTrack);
}
} catch (err) {
console.log(err);
log("Error in local video & audio: " + err);
}
log("Warmup completed");
}
function initiateCall(user) {
log("Start van video verzoek");
// Verander UI
//document.getElementById("main").style.display = "none";
//document.getElementById("call").style.display = "block";
log("Voor gebruiker: " + user);
voor = user;
log("Van gebruiker: " + document.getElementById("user").innerHTML);
van = document.getElementById("user").innerHTML;
started = true;
//offer(JSON.stringify({start: true}));
jQuery.post(
"offer", {
to: user,
from: document.getElementById("user").innerHTML,
start: true
},
function() { console.log("Offer sent!"); }
).error("initiateCall",error);
}
function endCall() {
log("Ending call");
document.getElementById("call").style.display = "none";
document.getElementById("main").style.display = "block";
document.getElementById("localvideo").mozSrcObject.stop();
document.getElementById("localvideo").mozSrcObject = null;
document.getElementById("remotevideo").mozSrcObject = null;
peerc.close();
peerc = null;
}
function error(from,e) {
if (typeof e == typeof {}) {
//alert("Oh no! " + JSON.stringify(e));
log("Oh no! " + from + " ERROR: " + JSON.stringify(e));
} else {
alert("Oh no!!!! " + from + " ERROR: " + e);
}
//endCall();
}
var users = [];
users.push(document.getElementById("user").innerHTML);
Please note that I combined examples for:
developer.mozilla.org
w3c.github.io
www.html5rocks.com
So there might be unnecessary code
If required, I can put all code in repository and share that for full view.
Additional logging shows the following errors:
DOMException: "Cannot add ICE candidate when there is no remote SDP"
InvalidModificationError: Cannot set local offer when createOffer has not been called.
You should try to use a TURN-Server. Even for usage in development. The traffic will be relayed if a direct P2P-connection can't be stablished.
Have a look at Coturn.
I can't say that this will be the solution for the current problem, but in my opinion most of the issues will be solved - and for production use, you will need it definitely.
I found the problem and solution.
First:
The STUN/TURN server was not a problem, this
urls: 'stun:stun.l.google.com:19302'
Is enough for local network development.
But I did install turnserver (ubuntu 18) which seems fine.
Second:
My problem was first in de message exchange, you need to make sure the OFFER/ANSWER go to right clients.
Last:
The negotiation needs to be stable before sending/receiving media.
I modified my code that connection and start video sending are separated.
Also this allows for just one side to send media or not.
I am new to the Opentok API and I am writing tests. In my tests I simulated disconnecting from the room and connecting again, but if I execute it at various times, the chat is runs slowly, until broken.
To init the chat I run $scope.initSession() and to disconnect I run $scope.disconnectFromSession().
I am using the Opentok.js version 2.13.2. See my following code:
var apiKey, sessionId, token;
apiKey = //my api key;
sessionId = //my sessionid;
token = //my token;
var session = null;
var publisher = null;
var stream = null;
var connectionCount = 0;
var publisherProperties = {frameRate: 7};
$scope.connected = false;
$scope.initSession = function() {
if (OT.checkSystemRequirements() == 1) {
// Initialize Session Object
session = OT.initSession(apiKey, sessionId);
createElement("publisher");
// initialize a publisher
publisher = OT.initPublisher('publisher', publisherProperties);
session.on({
streamCreated: function(event) {
console.log("EVENT streamCreated: " + event.stream.name + " - " + event.reason);
createElement("subscriber");
stream = event.stream;
session.subscribe(stream, 'subscriber');
},
streamDestroyed: function(event) {
event.preventDefault();
console.log("EVENT streamDestroyed: " + event.stream.name + " - " + event.reason);
console.log('Stream ${event.stream.name} ended because ${event.reason}.');
}
});
connectToSession();
} else {
console.log('Browser havenĀ“t support to WebRTC');
}
}
function connectToSession() {
session.connect(token, function(err) {
if (err) {
if (err.name === "OT_NOT_CONNECTED") {
showMessage('Failed to connect. Please check your connection and try connecting again.');
} else {
showMessage('An unknown error occurred connecting. Please try again later.');
}
} else {
// publish to the session
session.publish(publisher);
$scope.connected = true;
}
});
}
function createElement(id) {
console.log(document.getElementById(id));
if (document.getElementById(id) === null) {
var divPublisher = document.createElement("div");
divPublisher.setAttribute("id", id);
document.getElementById("div-videos").appendChild(divPublisher);
}
}
$scope.disconnectFromSession = function() {
session.disconnect();
$scope.connected = false;
OT.off();
}
$scope.initSession();
I appreciate any help.
I am new to WebRTC, I want to setup a video call by using web socket over node.js,I am Unable Display the Remote video screen but local video element works fine.
May be I am missing the flow which i could not figure it out.
I am posting my html code with java script here.
HTML Code
<!---display sharing screen--->
<div id="video_container" style="display:none;">
This Streams Remote Video
<video controls autoplay id="remotevideo"></video><br>
This Streams Local Video
<video controls autoplay id="local_video"></video>
</div>
The below is my javascript
var webrtc_capable = true;
var rtc_peer_connection = null;
var rtc_session_description = null;
var get_user_media = null;
var connect_stream_to_src = null;
var stun_server = "stun.l.google.com:19302";
if (navigator.getUserMedia) { // WebRTC 1.0 standard compliant browser
rtc_peer_connection = RTCPeerConnection;
rtc_session_description = RTCSessionDescription;
get_user_media = navigator.getUserMedia.bind(navigator);
connect_stream_to_src = function(media_stream, media_element) {
media_element.srcObject = media_stream;
media_element.play();
};
} else if (navigator.mozGetUserMedia) { // early firefox webrtc implementation
rtc_peer_connection = mozRTCPeerConnection;
rtc_session_description = mozRTCSessionDescription;
get_user_media = navigator.mozGetUserMedia.bind(navigator);
connect_stream_to_src = function(media_stream, media_element) {
media_element.mozSrcObject = media_stream;
media_element.play();
};
stun_server = "74.125.31.127:19302";
} else if (navigator.webkitGetUserMedia) { // early webkit webrtc implementation
rtc_peer_connection = webkitRTCPeerConnection;
rtc_session_description = RTCSessionDescription;
get_user_media = navigator.webkitGetUserMedia.bind(navigator);
connect_stream_to_src = function(media_stream, media_element) {
media_element.src = URL.createObjectURL(media_stream);
};
} else {
alert("This browser does not support WebRTC - visit WebRTC.org for more info");
webrtc_capable = false;
}
</script>
<!---Javascript for splitting screen--->
<script>
function splitScreen()
{
var z;
document.getElementById("chat").style.display="block";
z=document.getElementById("video_container");
z.className="videoContainer";
z.style.display="block";
}
var call_token; // unique token for this call
var signaling_server; // signaling server for this call
var local_peer_connection;
//function to establish webrtc connection
function start(){
peer_connection=new rtc_peer_connection({ // RTCPeerConnection configuration
"iceServers": [ // information about ice servers
{ "url": "stun:"+stun_server }, // stun server info
]
});
setup_video();
peer_connection.onicecandidate== function (ice_event) {
if (ice_event.candidate) {
signaling_server.send(
JSON.stringify({
token:call_token,
type: "new_ice_candidate",
candidate: ice_event.candidate ,
})
);
}
};
peer_connection.onaddstream=function(event){
//alert("remote video is getting called!!");
connect_stream_to_src(event.stream,document.getElementById("remotevideo"));
};
signaling_server = new WebSocket("ws://localhost:3455");
if (document.location.hash === "" || document.location.hash === undefined) { // you are the Caller
// create the unique token for this call
var token = Date.now()+"-"+Math.round(Math.random()*10000);
call_token = "#"+token;
// set location.hash to the unique token for this call
document.location.hash = token;
signaling_server.onopen = function() {
// setup caller signal handler
signaling_server.onmessage = caller_signal_handler;
// tell the signaling server you have joined the call
signaling_server.send(
JSON.stringify({
token:call_token,
type:"join",
})
);
}
document.title = "You are the Caller";
//document.getElementById("loading_state").innerHTML = "Ready for a call...ask your friend to visit:<br/><br/>"+document.location;
} else { // you have a hash fragment so you must be the Callee
// get the unique token for this call from location.hash
call_token = document.location.hash;
signaling_server.onopen = function() {
// setup caller signal handler
signaling_server.onmessage = callee_signal_handler;
// tell the signaling server you have joined the call
signaling_server.send(
JSON.stringify({
token:call_token,
type:"join",
})
);
// let the caller know you have arrived so they can start the call
signaling_server.send(
JSON.stringify({
token:call_token,
type:"callee_arrived",
})
);
}
document.title = "You are the Callee";
// document.getElementById("loading_state").innerHTML = "One moment please...connecting your call...";
}
// setup message bar handlers
document.getElementById("message_input").onkeydown = send_chat_message;
document.getElementById("message_input").onfocus = function() { this.value = ""; }
}
/* functions used above are defined below */
// handler to process new descriptions
function new_description_created(description) {
peer_connection.setLocalDescription(
description,
function () {
// connect_stream_to_src(event.stream,document.getElementById("remotevideo"));
signaling_server.send(
JSON.stringify({
token:call_token,
type:"new_description",
sdp:description
})
);
},
log_error
);
}
// handle signals as a caller
function caller_signal_handler(event) {
var signal = JSON.parse(event.data);
if (signal.type === "callee_arrived") {
peer_connection.createOffer(
new_description_created,
log_error
);
} else if (signal.type === "new_ice_candidate") {
peer_connection.addIceCandidate(
new RTCIceCandidate(signal.candidate)
);
} else if (signal.type === "new_description") {
peer_connection.setRemoteDescription(
new rtc_session_description(signal.sdp),
function () {
peer_connection.addStream(remotevideo);
connect_stream_to_src(event.stream, document.getElementById("remotevideo"));
if (peer_connection.remoteDescription.type == "answer") {
// extend with your own custom answer handling here
//connect_stream_to_src(remotevideo, document.getElementById("remotevideo"));
}
},
log_error
);
} else if (signal.type === "new_chat_message") {
add_chat_message(signal);
} else {
// extend with your own signal types here
}
}
// handle signals as a callee
function callee_signal_handler(event) {
var signal = JSON.parse(event.data);
if (signal.type === "new_ice_candidate") {
peer_connection.addIceCandidate(
new RTCIceCandidate(signal.candidate)
);
} else if (signal.type === "new_description") {
peer_connection.setRemoteDescription(
new rtc_session_description(signal.sdp),
function () {
if (peer_connection.remoteDescription.type == "offer") {
peer_connection.createAnswer(new_description_created, log_error);
connect_stream_to_src(event.stream, document.getElementById("remotevideo"));
}
},
log_error
);
} else if (signal.type === "new_chat_message") {
add_chat_message(signal);
}
}
// add new chat message to messages list
function add_chat_message(signal) {
var messages = document.getElementById("messages");
var user = signal.user || "them";
messages.innerHTML = user+": "+signal.message+"<br/>\n"+messages.innerHTML;
}
// send new chat message to the other browser
function send_chat_message(e) {
if (e.keyCode == 13)
{
var new_message = this.value;
this.value = "";
signaling_server.send(
JSON.stringify(
{
token:call_token,
type: "new_chat_message",
message: new_message
})
);
add_chat_message({ user: "you", message: new_message });
}
}
function setup_video()
{//alert("In setup_video function");
get_user_media({
"audio":true,
"video":true
},
function (local_stream) { // success callback
// display preview from the local camera & microphone using local <video> MediaElement
connect_stream_to_src(local_stream, document.getElementById("local_video"));
// add local camera stream to peer_connection ready to be sent to the remote peer
peer_connection.addStream(local_stream);
},
log_error
);
}
// generic error handler
function log_error(error) {
console.log(error);
}
Server.js
// useful libs
var http = require("http");
var fs=require("fs");
var websocket = require("websocket").server;
// general variables
var port = 3455;
var webrtc_clients = [];
var webrtc_discussions = {};
// web server functions
var http_server = http.createServer(function(request, response) {
var matches = undefined;
if (matches = request.url.match("^/images/(.*)")) {
var path = process.cwd()+"/images/"+matches[1];
fs.readFile(path, function(error, data) {
if (error) {
log_error(error);
} else {
response.end(data);
}
});
} else {
response.end(page);
}
});
http_server.listen(port, function() {
log_comment("server listening (port "+port+")");
});
var page = undefined;
fs.readFile("htmlfilename",function(error,data){
if(error){
log_comment(error);
}
else{
page=data;
}
});
// web socket functions
var websocket_server = new websocket({
httpServer: http_server
});
websocket_server.on("request", function(request) {
log_comment("new request ("+request.origin+")");
var connection = request.accept(null, request.origin);
log_comment("new connection ("+connection.remoteAddress+")");
webrtc_clients.push(connection);
connection.id = webrtc_clients.length-1;
connection.on("message", function(message) {
if (message.type === "utf8") {
log_comment("got message "+message.utf8Data);
var signal = undefined;
try { signal = JSON.parse(message.utf8Data); } catch(e) { };
if (signal) {
if (signal.type === "join" && signal.token !== undefined) {
try {
if (webrtc_discussions[signal.token] === undefined) {
webrtc_discussions[signal.token] = {};
}
} catch(e) { };
try {
webrtc_discussions[signal.token][connection.id] = true;
} catch(e) { };
} else if (signal.token !== undefined) {
try {
Object.keys(webrtc_discussions[signal.token]).forEach(function(id) {
if (id != connection.id) {
webrtc_clients[id].send(message.utf8Data, log_error);
}
});
} catch(e) { };
} else {
log_comment("invalid signal: "+message.utf8Data);
}
} else {
log_comment("invalid signal: "+message.utf8Data);
}
}
});
connection.on("close", function(connection) {
log_comment("connection closed ("+connection.remoteAddress+")");
Object.keys(webrtc_discussions).forEach(function(token) {
Object.keys(webrtc_discussions[token]).forEach(function(id) {
if (id === connection.id) {
delete webrtc_discussions[token][id];
}
});
});
});
});
// utility functions
function log_error(error) {
if (error !== "Connection closed" && error !== undefined) {
log_comment("ERROR: "+error);
}
}
function log_comment(comment) {
console.log((new Date())+" "+comment);
}
Error:
The connection to wss://localhost:28443/Administration/sessionCheck?d22c6c8e-61b4-41d3-b447-6436b5b631c9 was interrupted while the page was loading.
I am new to websocket,angular js.Using websocket in the single page - web application to understand whether the server is alive.
In this when I try use window.location.assign(url) to download the zip from the application on firefox the websocket connectivity is lost & i have tried to search this on this forum but i didn't got matched answer.
Websocket is interrupted when i use window.location.assign(url) page on firefox. This works seamless on chrome and IE.
I have also implemented the fixed on the client side by checking on window load if the socket is open or not:
Inside the controller
window.onbeforeunload = function () {
$scope.webSocketFinalize();
};
Main Controler code
function webSocketProvider($scope, $location, $window, heartbeat_interval, $translate, $timeout) {
$scope.websocketHB = null;
$scope.startWebSocketHeartBeat = function(headerValue){
var wsUri = "wss://"+window.location.host +
window.location.pathname+"severHeartBeat?"+headerValue;
var heartbeat_msg = '--heartbeat--', missed_heartbeats = 0;
websocketHB = new WebSocket(wsUri);
console.log("message 1....: startWebSocketHeartBeat"+websocketHB);
websocketHB.onopen = function(evt) {
console.log("opening...2..........");
if (heartbeat_interval === null) {
missed_heartbeats = 0;
heartbeat_interval = setInterval(function() {
try {
missed_heartbeats++;
if (missed_heartbeats >= 3){
clearInterval(heartbeat_interval);
heartbeat_interval = null;
console.log("Closing connection. Reason: ");
websocketHB.close();
window.location.href = '/Administration';
$routeParams.auth = '';
}else{
try{
if(websocketHB.readyState == 1 || websocketHB.readyState == 0){
websocketHB.send(heartbeat_msg);
}
}catch(e){}
}
} catch(e) {
clearInterval(heartbeat_interval);
heartbeat_interval = null;
console.log("Closing connection. Reason: " + e.message);
websocketHB.close();
}
}, 5000);
}
};
websocketHB.onmessage = function(evt) {
console.log("message 3....: startWebSocketHeartBeat"+evt.data);
if(evt.data == "--heartbeat--") {
missed_heartbeats = 0;
}else{
console.log("Send Failed:");
}
};
websocketHB.onerror = function(evt) {
console.log("ERROR:4 " + evt.data);
};
};
$scope.webSocketFinalize = function() {
if(null!=$scope.websocketHB){
$scope.websocketHB.close();
}
};
};
I need to batch change a number of image links (URL's links that exist within a class in) to image files (that Parse.com hosts).
Cloud code is (apparently) how to do it.
I've followed the documentation here but haven't had any success.
What I wanted to do is:
Take URL link from "COLUMN_1"
Make it a file
Upload file to "COLUMN_1" (overwrite existing URL). If this is dangerous- can upload it to a new column ("COLUMN_2").
Repeat for next row
This code did not work (this is my first time with JS):
imgFile.save().then(function () {
object.set("COLUMN_1", imgFile);
return object.save();
}).then(function (CLASSNAME) {
response.success("saved object");
}, function (error) {
response.error("failed to save object");
});
Can anyone recommend how to do this?
OK- this successfully works for anyone else trying.
Parse.Cloud.job("convertFiles", function(request, status) { //Cuts the rundata out of poor runs
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
// Tell the JS cloud code to keep a log of where it's upto. Manually create one row (in class "debugclass") to get an object Id
Parse.Cloud.useMasterKey();
var Debug = Parse.Object.extend("debugclass");
var queryForDebugObj = new Parse.Query(Debug);
queryForDebugObj.equalTo("objectId", "KbwwDV2S57");
// Query for all users
// var queryForSublist = new Parse.Query(Parse.Object.extend("gentest"));
queryForDebugObj.find({
success: function(results) {
var debugObj = results[0];
var processCallback = function(res) {
var entry = res[0];
var debugObj = results[0];
debugObj.set("LastObject", entry.id);
debugObj.save();
Parse.Cloud.httpRequest({
url: entry.get("smallImage2"),
method: "GET",
success: function(httpImgFile)
{
console.log("httpImgFile: " + String(httpImgFile.buffer));
var imgFile = new Parse.File("picture.jpg", {base64: httpImgFile.buffer.toString('base64')});
imgFile.save().then(function () {
console.log("2");
entry.set("smallImage1", imgFile);
entry.save(null, {
success: function(unused) {
debugObj.increment("itemDone");
sleep(20);
res.shift();
if (res.length === 0) {
process(entry.id);
return;
}
else {
processCallback(res);
}
},
error: function(unused, error) {
response.error("failed to save entry");
}
});
});
},
error: function(httpResponse)
{
console.log("unsuccessful http request");
response.error(responseString);
}
});
};
var process = function(skip) {{
var queryForSublist = new Parse.Query("genpants");
if (skip) {
queryForSublist.greaterThan("objectId", skip);
console.error("last object retrieved:" + skip);
}
queryForSublist.ascending("objectId");
queryForSublist.find().then(function querySuccess(res) {
processCallback(res);
}, function queryFailed(reason) {
status.error("query unsuccessful, length of result " + result.length + ", error:" + error.code + " " + error.message);
});
}};
process(debugObj.get("LastObject"));
},
error: function(error) {
status.error("xxx Uh oh, something went wrong 2:" + error + " " + error.message);
}
});
});