-
Notifications
You must be signed in to change notification settings - Fork 1
Socket.io
The cloud-node API has the socket.io code that communicates with both the magic mirror and the phone. Until you get used to it, it seems pretty magical--sometimes even when you are used to it.
The socket.io code in the cloud-node is in this file: socket.io stuff
The basic idea of socket.io is that all the clients connected to the socket, can 'hear' a message emitted like this:
socket.emit("message", {user: bessie, text: "hello"})
You get to define the value of both the first parameter, 'message' in the case above, and the second parameter, which is the data.
What happens to connect the mirror and the phone is the mirror generates a 4 digit code and broadcasts it like this:
socket.emit('mirror', code);
Meanwhile, in cloud-node, it listens for this message and saves it and the socketId that it came from. This file has an array of objects (called clients) that look like this:
{
"mirrorSocketId": long string,
"code": string
}
If a phone wants to connect to the mirror, it does this:
socket.emit('phone', code);
The cloud-node is going to see this message and look through its clients array to find that code. When it finds it, it will change the object to this:
{
"mirrorSocketId": long string,
"code": string,
"phoneSockeId": long string
}
So, now there is a link between the mirror that generated a code, and a phone app where the user entered the code. When the link is made, it will tell the phone and the mirror they are connected. To 'contact' the specific mirror application it will do this:
socket.broadcast.to(mirrorSocketId).emit('phoneConnected', socket.id);
So, the mirror can listen for the phoneConnected message and get the phone's socketId. At the same time, this command:
socket.emit('mirrorConnected', mirrorSocketId);
will allow the phone to listen to 'mirrorConnected' message and get the mirror's socketId.