sumorobot-web/assets/js/sumorobot.js

99 lines
3.3 KiB
JavaScript
Executable File

// Sumorobot constructor
var Sumorobot = function(wsUri, robotId) {
// Assign the WebSocket URI
this.wsUri = wsUri;
// Assign the SumoRobot ID
this.robotId = robotId;
// To keep track of the WebSocket connection
this.watchdogTimer = 0;
// Timer to ping the SumoRobot
this.watchdogTimer = null;
// To store Blockly code
this.blocklyCode = "";
// Start connecting to the WebSocket
this.connect();
};
// Function to initiate the WebSocket connection
Sumorobot.prototype.connect = function() {
// To have access to this object inside events
var self = this;
this.websocket = new WebSocket(this.wsUri);
// Setup connection watchdog interval
setInterval(function() {
if (self.watchdogCounter == 0) {
$("#battery").removeClass("connected");
$("#battery").html("Disconnected");
}
// Reset watchdog counter
self.watchdogCounter = 0;
}, 3000);
// When the WebSocket gets connected
this.websocket.onopen = function(evt) {
// Send authentication packet
self.websocket.send(`{"setID": "browser-${self.robotId}@00000514", "passwd": "salakala"}`);
// Setup a timer to ping the robot
self.watchdogTimer = setInterval(function() {
// Send a ping to the robot
self.send(self.robotId, "ping");
}, 500);
};
// When the WebSocket closes
this.websocket.onclose = function(evt) {
// Clear the pinging
clearInterval(self.watchdogTimer);
// Try to recnnect to the sumorobot
self.connect();
};
// When there is a message from the WebSocket
this.websocket.onmessage = function(evt) {
// When scope is received
var data = evt.data.replace(/'/g, '"').toLowerCase();
// Get SumoRobot battery voltage
var battery = JSON.parse(data)["battery_voltage"];
// When sensor data received
if (battery) {
$("#battery").html(battery + "V");
$("#battery").addClass("connected");
}
// Count data received packets
self.watchdogCounter += 1;
};
// When there is an WebSocket error
this.websocket.onerror = function(err) {
console.log("ERROR websocket error: " + err);
};
};
// Function to send WebSocket data
Sumorobot.prototype.send = function(msg, val) {
// Ready state constants: CONNECTING 0, OPEN 1, CLOSING 2, CLOSED 3
// https://developer.mozilla.org/en-US/docs/Web/API/WebSocket
if (this.websocket.readyState == 1) {
if (val === 'undefined') {
this.websocket.send(`{"to": "sumo-${this.robotId}@00000514", "cmd": "${msg}"}`);
} else {
this.websocket.send(`{"to": "sumo-${this.robotId}@00000514", "cmd": "${msg}", "val": "${val}"}`);
}
}
};
// Function to close the WebSocket connection
Sumorobot.prototype.close = function() {
// When a WebSocket connection exists
if (this.websocket !== 'undefined') {
// Close the WebSocket connection
this.websocket.close();
}
};
// Function to get SumoRobot Blockly code
Sumorobot.prototype.getBlocklyCode = function() {
return this.blocklyCode;
};
// Function to set SumoRobot Blockly code
Sumorobot.prototype.setBlocklyCode = function(blocklyCode) {
this.blocklyCode = blocklyCode;
};