Fixed geo-dashoard stream connection issue

revert-70aa11f8
lasantha 7 years ago
parent 149901828a
commit 8376948013

@ -17,30 +17,38 @@
*/
function onRequest(context) {
var log = new Log("geo-dashboard.js");
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var viewModel = {};
var carbonServer = require("carbon").server;
var device = context.unit.params.device;
var constants = require("/app/modules/constants.js");
var wsEndpoint = devicemgtProps["wssURL"].replace("https", "wss") + "/secured-websocket/t/";
var spatialWSEndpoint = devicemgtProps["wssURL"].replace("https", "wss");
var alertsWSEndpoint = devicemgtProps["wssURL"].replace("https", "wss");
var wsEndpoint = null;
var jwtService = carbonServer.osgiService(
'org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService');
var jwtClient = jwtService.getJWTClient();
var encodedClientKeys = session.get(constants["ENCODED_TENANT_BASED_WEB_SOCKET_CLIENT_CREDENTIALS"]);
var tokenPair = null;
var token = "";
if (encodedClientKeys) {
var tokenUtil = require("/app/modules/oauth/token-handler-utils.js")["utils"];
var resp = tokenUtil.decode(encodedClientKeys).split(":");
var tokenPair = jwtClient.getAccessToken(resp[0], resp[1], context.user.username, "default", {});
if (tokenPair) {
token = tokenPair.accessToken;
if (context.user.domain == "carbon.super") {
tokenPair = jwtClient.getAccessToken(resp[0], resp[1], context.user.username,"default", {});
if (tokenPair) {
token = tokenPair.accessToken;
wsEndpoint = devicemgtProps["wssURL"].replace("https", "wss") + "/secured-websocket/";
}
} else {
tokenPair = jwtClient.getAccessToken(resp[0], resp[1], context.user.username + "@" + context.user.domain,"default", {});
if (tokenPair) {
token = tokenPair.accessToken;
wsEndpoint = devicemgtProps["wssURL"].replace("https", "wss") + "/secured-websocket/t/"+context.user.domain+"/";
}
}
}
viewModel.device = device;
viewModel.wsToken = token;

@ -46,6 +46,65 @@ function processPointMessage(geoJsonFeature) {
}
}
window.onbeforeunload = function () {
disconnect();
};
function initializeSpatialStreamWebSocket() {
spatialWebsocket = new WebSocket(webSocketURL);
spatialWebsocket.onopen = webSocketSpatialOnOpen;
spatialWebsocket.onmessage = webSocketSpatialOnMessage;
spatialWebsocket.onclose = webSocketSpatialOnClose;
spatialWebsocket.onerror = webSocketSpatialOnError;
}
function initializeOnAlertWebSocket() {
onAlertWebsocket = new WebSocket(alertWebSocketURL);
onAlertWebsocket.onmessage = webSocketOnAlertMessage;
onAlertWebsocket.onclose = webSocketOnAlertClose;
onAlertWebsocket.onerror = webSocketOnAlertError;
onAlertWebsocket.onopen = webSocketOnAlertOpen;
}
function initializeGeoLocation(geoFencingEnabled) {
var deviceDetails = $(".device-id");
deviceId = deviceDetails.data("deviceid");
deviceType = deviceDetails.data("type");
if (deviceId && deviceType) {
var geoCharts = $("#geo-charts");
var wsEndPoint = geoCharts.data("ws-endpoint");
wsToken = geoCharts.data("ws-token");
geoPublicUri = geoCharts.data("geo-public-uri");
geoPublicUri = geoCharts.data("geo-public-uri");
webSocketURL = wsEndPoint + "iot.per.device.stream.geo.FusedSpatialEvent/1.0.0?"
+ "deviceId=" + deviceId + "&deviceType=" + deviceType + "&websocketToken=" + wsToken;
alertWebSocketURL = wsEndPoint + "iot.per.device.stream.geo.AlertsNotifications/1.0.0?"
+ "deviceId=" + deviceId + "&deviceType=" + deviceType + "&websocketToken=" + wsToken;
$("#proximity_alert").hide();
if (geoFencingEnabled) {
disconnect();
initializeSpatialStreamWebSocket();
initializeOnAlertWebSocket();
}
initialLoad(geoFencingEnabled);
InitSpatialObject(geoFencingEnabled);
} else {
noty({text: 'Invalid Access! No device information provided to track!', type: 'error'});
}
}
function disconnect(){
if (spatialWebsocket && spatialWebsocket.readyState == spatialWebsocket.OPEN){
spatialWebsocket.close();
}
if (onAlertWebsocket && onAlertWebsocket.readyState == onAlertWebsocket.OPEN){
onAlertWebsocket.close();
}
}
function SpatialObject(json) {
this.id = json.id;
this.type = json.properties.type;
@ -97,7 +156,7 @@ SpatialObject.prototype.update = function (geoJSON) {
/*
//This is implemented in alertWebSocket
if (this.state != "NORMAL") {
notifyAlert("Object ID: <span style='color: blue;cursor: pointer' onclick='focusOnSpatialObject(" + this.id + ")'>" + this.id + "</span> change state to: <span style='color: red'>" + geoJSON.properties.state + "</span> Info : " + this.information);
notifyArt("Object ID: <span style='color: blue;cursor: pointer' onclick='focusOnSpatialObject(" + this.id + ")'>" + this.id + "</span> change state to: <span style='color: red'>" + geoJSON.properties.state + "</span> Info : " + this.information);
}*/
var newLineStringGeoJson = this.createLineStringFeature(this.state, this.information, [this.latitude, this.longitude]);
this.pathGeoJsons.push(newLineStringGeoJson);
@ -175,7 +234,6 @@ SpatialObject.prototype.removeFromMap = function () {
function clearMap() {
for (var spacialObject in currentSpatialObjects) {
console.log(spacialObject);
currentSpatialObjects[spacialObject].removePath();
currentSpatialObjects[spacialObject].removeFromMap();
}
@ -199,7 +257,6 @@ SpatialObject.prototype.createLineStringFeature = function (state, information,
SpatialObject.prototype.setSpeed = function (speed) {
this.speed = speed;
this.speedHistory.push(speed);
// console.log("DEBUG: this.speedHistory.length = "+this.speedHistory.length+" ApplicationOptions.constance.SPEED_HISTORY_COUNT = "+ApplicationOptions.constance.SPEED_HISTORY_COUNT);
if (this.speedHistory.length > ApplicationOptions.constance.SPEED_HISTORY_COUNT) {
this.speedHistory.splice(1, 1);
}
@ -227,7 +284,6 @@ SpatialObject.prototype.drawPath = function () {
var currentSection = new L.polyline(this.pathGeoJsons[lineString].geometry.coordinates, this.getSectionStyles(currentSectionState)); // Create path object when and only drawing the path (save memory) TODO: if need directly draw line from geojson
var currentSectionFirstPoint = this.pathGeoJsons[lineString].geometry.coordinates[0];
console.log("DEBUG: previousSectionLastPoint = " + previousSectionLastPoint + " currentSectionFirstPoint = " + currentSectionFirstPoint);
previousSectionLastPoint.push(currentSectionFirstPoint);
var sectionJoin = new L.polyline(previousSectionLastPoint, this.getSectionStyles());
sectionJoin.setStyle({className: "sectionJointStyle"});// Make doted line for section join , this class is currently defined in map.jag as a inner css
@ -235,7 +291,6 @@ SpatialObject.prototype.drawPath = function () {
previousSectionLastPoint = [this.pathGeoJsons[lineString].geometry.coordinates[this.pathGeoJsons[lineString].geometry.coordinates.length - 1]];
sectionJoin.addTo(map);
this.path.push(sectionJoin);
console.log("DEBUG: Alert Information: " + this.pathGeoJsons[lineString].properties.information);
currentSection.bindPopup("Alert Information: " + this.pathGeoJsons[lineString].properties.information);
currentSection.addTo(map);
this.path.push(currentSection);
@ -278,7 +333,6 @@ function processTrafficMessage(json) {
if (json.id in currentSpatialObjects) {
var existingObject = currentSpatialObjects[json.id];
existingObject.update(json);
console.log("existing area");
}
else {
var receivedObject = new GeoAreaObject(json);
@ -289,7 +343,6 @@ function processTrafficMessage(json) {
function processAlertMessage(json) {
if (json.state != "NORMAL" && json.state != "MINIMAL") {
console.log(json);
notifyAlert("Object ID: <span style='color: blue;cursor: pointer' onclick='focusOnSpatialObject(" + json.id + ")'>" + json.id + "</span> change state to: <span style='color: red'>" + json.state + "</span> Info : " + json.information);
}
}
@ -302,9 +355,7 @@ function processAlertMessage(json) {
var type = typeof o;
return type === 'object' || type === 'function';
}
if (!isObject(obj)) return;
var prop;
for (var i=1; i < arguments.length-1; i++)
{
@ -312,13 +363,11 @@ function processAlertMessage(json) {
if (!isObject(obj[prop])) obj[prop] = {};
if (i < arguments.length-2) obj = obj[prop];
}
obj[prop] = arguments[i];
}*/
function processPredictionMessage(json) {
setPropertySafe(currentPredictions, json.day, json.hour, json.longitude, json.latitude, json.traffic - 1);
//console.log(json);
}
WebSocket.prototype.set_opened = function () {
@ -334,9 +383,7 @@ WebSocket.prototype.get_opened = function () {
var _longitudeStart = -0.0925
var _latitudeStart = 51.4985
var _unit = 0.005;
function requestPredictions(longitude, latitude, d) {
var serverUrl = "http://localhost:9763/endpoints/GpsDataOverHttp/predictionInput";
function loop(i) {
setTimeout(function() {
@ -362,7 +409,6 @@ WebSocket.prototype.get_opened = function () {
}
var d= new Date();
//requestPredictions(-0.09,51.5,d);
function getPredictions(longitude, latitude, d) {
var longitude = Math.round((longitude - _longitudeStart)/_unit);
var latitude = Math.round((latitude - _latitudeStart)/_unit);
@ -379,7 +425,6 @@ WebSocket.prototype.get_opened = function () {
traffic[0][i+1] = hour;
traffic[1][i+1] = currentPredictions[day][hour][longitude][latitude];
} catch(e) {
console.log(i);
}
}
return traffic;
@ -440,7 +485,6 @@ GeoAreaObject.prototype.update = function (geoJSON) {
this.marker.setIconAngle(this.heading);
this.marker.setIcon(this.stateIcon());
console.log("update called");
// TODO: use general popup DOM
this.popupTemplate.find('#objectId').html(this.id);
this.popupTemplate.find('#information').html(this.information);
@ -509,7 +553,6 @@ function LocalStorageArray(id) {
var initLoading = true;
var webSocketOnAlertOpen = function () {
onAlertWebsocket.set_opened();
$('#ws-alert-stream').removeClass('text-muted text-danger text-success').addClass('text-success');
};
@ -518,26 +561,18 @@ var webSocketOnAlertMessage = function processMessage(message) {
var json = $.parseJSON(message.data);
if (json.messageType == "Alert") {
processAlertMessage(json);
} else {
console.log("Message type not supported.");
}
}
};
var webSocketOnAlertClose = function (e) {
if (onAlertWebsocket.get_opened()) {
$('#ws-alert-stream').removeClass('text-muted text-danger text-success').addClass('text-danger');
}
waitForSocketConnection(onAlertWebsocket, initializeOnAlertWebSocket);
};
var webSocketOnAlertError = function (e) {
if (!onAlertWebsocket.get_opened()) return;
noty({text: 'Something went wrong when trying to connect to <b>' + alertWebSocketURL + '<b/>', type: 'error'});
};
var webSocketSpatialOnOpen = function () {
spatialWebsocket.set_opened();
if (initLoading) {
initLoading = false;
}
@ -558,94 +593,13 @@ var webSocketSpatialOnMessage = function (message) {
};
var webSocketSpatialOnClose = function (e) {
if (spatialWebsocket.get_opened()) {
$('#ws-spatial-stream').removeClass('text-muted text-danger text-success').addClass('text-danger');
}
waitForSocketConnection(spatialWebsocket, initializeSpatialStreamWebSocket);
};
var webSocketSpatialOnError = function (err) {
if (!spatialWebsocket.get_opened()) return;
noty({text: 'Something went wrong when trying to connect to <b>' + webSocketURL + '<b/>', type: 'error'});
};
var waitTime = 1000;
var waitQueue = {};
function waitForSocketConnection(socket, callback) {
if(waitQueue[socket.url]) return;
setTimeout(
function () {
if (socket.readyState === 1) {
//connectToSource();
console.log("Connection is made");
if (callback != null) {
callback();
}
return;
} else {
ws = new WebSocket(socket.url);
if(socket)socket.close();
waitTime += 400;
waitForSocketConnection(ws, callback);
}
}, waitTime); // wait 5 milisecond for the connection...
waitQueue[socket.url] = true;
}
function initializeSpatialStreamWebSocket() {
if(spatialWebsocket) spatialWebsocket.close();
spatialWebsocket = new WebSocket(webSocketURL);
spatialWebsocket.onopen = webSocketSpatialOnOpen;
spatialWebsocket.onmessage = webSocketSpatialOnMessage;
spatialWebsocket.onclose = webSocketSpatialOnClose;
spatialWebsocket.onerror = webSocketSpatialOnError;
}
function initializeOnAlertWebSocket() {
if(onAlertWebsocket) onAlertWebsocket.close();
onAlertWebsocket = new WebSocket(alertWebSocketURL);
onAlertWebsocket.onmessage = webSocketOnAlertMessage;
onAlertWebsocket.onclose = webSocketOnAlertClose;
onAlertWebsocket.onerror = webSocketOnAlertError;
onAlertWebsocket.onopen = webSocketOnAlertOpen;
}
function initializeGeoLocation(geoFencingEnabled) {
var deviceDetails = $(".device-id");
deviceId = deviceDetails.data("deviceid");
deviceType = deviceDetails.data("type");
var loggedInUser = $("#logged-in-user");
var username = loggedInUser.data("username");
var userDomain = loggedInUser.data("domain");
if (deviceId && deviceType) {
var geoCharts = $("#geo-charts");
var wsEndPoint = geoCharts.data("ws-endpoint");
wsToken = geoCharts.data("ws-token");
geoPublicUri = geoCharts.data("geo-public-uri");
webSocketURL = wsEndPoint + userDomain + "/iot.per.device.stream.geo.FusedSpatialEvent/1.0.0?"
+ "deviceId=" + deviceId + "&deviceType=" + deviceType + "&websocketToken=" + wsToken;
alertWebSocketURL = wsEndPoint + userDomain + "/org.wso2.geo.AlertsNotifications/1.0.0?"
+ "deviceId=" + deviceId + "&deviceType=" + deviceType + "&websocketToken=" + wsToken;
$("#proximity_alert").hide();
initialLoad(geoFencingEnabled);
InitSpatialObject(geoFencingEnabled);
if (geoFencingEnabled) {
initializeSpatialStreamWebSocket();
initializeOnAlertWebSocket();
window.onbeforeunload = function () {
spatialWebsocket.close();
onAlertWebsocket.close();
}
}
} else {
noty({text: 'Invalid Access! No device information provided to track!', type: 'error'});
}
}
SpatialObject.prototype.stateIcon = function () {
//TODO : Need to add separate icons for each device type
var iconUrl = geoPublicUri + "/img/markers/object-types/default";
@ -656,19 +610,18 @@ SpatialObject.prototype.stateIcon = function () {
}
return L.icon({
iconUrl: iconUrl + ".png",
shadowUrl: false,
iconSize: [24, 24],
iconAnchor: [+12, +12],
popupAnchor: [-2, -5]
});
iconUrl: iconUrl + ".png",
shadowUrl: false,
iconSize: [24, 24],
iconAnchor: [+12, +12],
popupAnchor: [-2, -5]
});
};
var normalMovingIcon = L.icon({
iconUrl: ApplicationOptions.leaflet.iconUrls.normalMovingIcon,
shadowUrl: false,
iconSize: [24, 24],
iconAnchor: [+12, +12],
popupAnchor: [-2, -5]
});
iconUrl: ApplicationOptions.leaflet.iconUrls.normalMovingIcon,
shadowUrl: false,
iconSize: [24, 24],
iconAnchor: [+12, +12],
popupAnchor: [-2, -5]
});
Loading…
Cancel
Save