Backend code

The entire backend code is written in JavaScript and it is in the server.js file.

To create the server, the module provided by socket.io is used because socket.io provides real-time bi-directional event-based communication:

var server = http.createServer(app);
var io = require('socket.io').listen(server);    

To receive messages, it is necessary to add a handler for them. In the 'connection' event, when a message is received it means that a new ESP8266 acceleration module wants to connect to the server. Values for the ID and socket are retrieved from the 'data' and added to the local list of previously connected ESP8266 acceleration modules:  

socket.on('connection', function (data) 
 {
   var acc_ram = new Object();
   acc_ram.socket_id = socket.id;
   var data_json = ParseJson(JSON.stringify(data));  
   acc_ram.acc_id = data_json.acc_id; 
   acc_ram.socket = socket;
   addACCObject(acc_ram);
   printACC();
   for(var webBrowsers = 0; webBrowsers < webConnections.length; webBrowsers++)
    {
      var sessionID = webConnections[webBrowsers].socket;
      sessionID.emit('acc_ram', { acc_ram: data })    
    }
    });   

To inform all the connected browsers that a new ACC is ready to send data, the backend server code sends an acc_ram message to them and forwards the data object that contains the module ID.

On receipt of the message, the browser will construct dynamically graphical elements (canvas for drawing, buttons) for the new module.

When the JSON message type that contains values for the measured acceleration is received by the backend, the message is forwarded to all the browsers, and the values will become input data for the smoothie.js graphics:

socket.on('JSON', function (data) 
 {
 for(var webBrowsers = 0; webBrowsers < webConnections.length; webBrowsers++)
 {
  //send data to all connected browsers
  var sessionID = webConnections[webBrowsers].socket; 
   sessionID.emit('acc_data', { acc_data: data });
 }
 });

For the messages received from the web page that are addressed to a specific ESP8266 module, we need to identify first the destination module based on the socket ID and send that message to the right module. Otherwise a reset command will be sent to all ESP8266 modules and I am sure that this is not what you intended to do:

socket.on('resetModule' , function (data)
  {
    for(var j=0; j< accConnections.length; j++)
   {
   var acc_m = accConnections[j];
      if(acc_m.acc_id == data.acc_id)
   {
    var s = acc_m.socket; //Get the socket
     s.emit("resetModule", {message: data} );
     return; //======>
   }
  } 
  });     
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.8.42