diff --git a/assets/js/sumorobot.js b/assets/js/sumorobot.js index 980b3c2..cbca50b 100755 --- a/assets/js/sumorobot.js +++ b/assets/js/sumorobot.js @@ -6,12 +6,19 @@ var Sumorobot = function(wsUri, robotId) { this.robotId = robotId; // To keep track of the WebSocket connection this.watchdogCounter = 0; - // Timer to ping the SumoRobot - this.watchdogTimer = null; + // When connection was intentionally closed + this.terminate = false; // To store Blockly code this.blocklyCode = ''; // If robot is moving this.moving = false; + // Sensor data + this.sensors = { + 'opponent': 99, + 'line_left': 0, + 'line_right': 0, + 'battery_voltage': 0 + }; // Start connecting to the WebSocket this.connect(); }; @@ -22,8 +29,8 @@ Sumorobot.prototype.connect = function() { var self = this; this.websocket = new WebSocket(this.wsUri); // Setup connection watchdog interval - setInterval(function() { - if (self.watchdogCounter == 0) { + self.connectionTimer = setInterval(function() { + if (self.watchdogCounter == 0 && !self.terminate) { $('#battery').removeClass('connected'); $('#battery').html('Disconnected'); } @@ -42,20 +49,24 @@ Sumorobot.prototype.connect = function() { }; // When the WebSocket closes this.websocket.onclose = function(evt) { - // Clear the pinging + // Clear the timers clearInterval(self.watchdogTimer); + clearInterval(self.connectionTimer); // Try to recnnect to the sumorobot - self.connect(); + // Only if the connection wasn't closed intentionally + if (!self.terminate) { + 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 batVolt = JSON.parse(data)['battery_voltage']; + self.sensors = JSON.parse(data); // When sensor data received - if (batVolt) { - $('#battery').html(batVolt + 'V'); + if (self.sensors['battery_voltage']) { + $('#battery').html(self.sensors['battery_voltage'] + 'V'); $('#battery').addClass('connected'); } // Count data received packets @@ -76,7 +87,7 @@ Sumorobot.prototype.send = function(cmd, 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 (!this.terminate && this.websocket.readyState == 1) { if (val) { this.websocket.send(`{"to": "sumo-${this.robotId}@00000514", "cmd": "${cmd}", "val": "${val}"}`); } else { @@ -87,6 +98,7 @@ Sumorobot.prototype.send = function(cmd, val) { // Function to close the WebSocket connection Sumorobot.prototype.close = function() { + this.terminate = true; // Close the WebSocket connection this.websocket.close(); };