Handling the events in the server

Now that we have animations and our web pages ready, let's handle the emitted events in our server:

  • When the user presses the Play button in the controls web page, it will emit an event, requesting the animation to start. When the server receives this event, it needs to notify the player to start. By its turn, the player, on changing the status to playing, will emit its current status, which must be captured by the server and used to play the LED strip animation.
  • When the user presses the Stop button in the controls web page, the server will receive it and will notify the player to stop playing the video. When the player status changes, the server will be notified to stop the LED strip animation.
  • When the Skip button is pressed in the controls web page, the server stops the LED animation immediately and notifies the player to skip to the next playlist video. On changing the player status, the server will be notified to start the LED animation again.

Edit your index.js file by typing vi index.js and paste the following code to the end of the file:

io.on('connection', function (socket) {
  socket.on('action', function (data) {
    if (data === 'play') io.sockets.emit('video', 'play'),
    if (data === 'stop') io.sockets.emit('video', 'stop'),
    if(data === 'next') {
      animation.stop();
      // Broadcast to all connected sockets
      io.sockets.emit('video', 'next'),
    }   
  });

  socket.on('video', function (data) {
    if (data === 'started') {
      animation.start();
      // Broadcast to all connected sockets
      io.sockets.emit('status', 'playing'),
    }

    if (data === 'stopped') {
      animation.stop();
      // Broadcast to all connected sockets
      io.sockets.emit('status', 'stopped'),
    }

  });
});

Now we should be able to handle all the events and coordinate all the system. On receiving an event, we'll reply using io.sockets.emit(), which allows us to emit an event to all the connected sockets.

On the top of the file, we also need to import the animations file to be able to use it by requiring it and assigning it to a var:

var animation = require('./animations'),

Now we are ready to test the whole system. Start the server with the command node index.js. On the same network as Galileo, open a browser in your computer with the URL http://my_ip_address:8080/player and another one in your mobile phone with the URL http://my_ip_address:8080/controls.

Using the control web page in your mobile phone, you'll be able to start, stop, or skip the animations along with the music videos.

..................Content has been hidden....................

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