Search icon CANCEL
Subscription
0
Cart icon
Cart
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Raspberry Pi 3 Home Automation Projects

You're reading from  Raspberry Pi 3 Home Automation Projects

Product type Book
Published in Nov 2017
Publisher Packt
ISBN-13 9781783283873
Pages 226 pages
Edition 1st Edition
Languages
Authors (2):
Shantanu Bhadoria Shantanu Bhadoria
Profile icon Shantanu Bhadoria
Ruben Oliva Ramos Ruben Oliva Ramos
Profile icon Ruben Oliva Ramos
View More author details
Toc

The Magic Mirror

The project was first put together by Michael Teeuw in 2014 and has since garnered much popularity in the maker community, inspiring smart mirror projects created by the average laymen. The project is open source and community-driven, enabling all users to download, edit, and create using this framework. On the most basic level, the Magic Mirror program is run on the Raspberry Pi, typically connected to a monitor specifically designated for this project.

The user then programs the Magic Mirror interface to his or her liking, adding functions such as e-mail notifications, NFL scores, weather alerts, reminders, and additional text. Once the Magic Mirror is set up to your liking, it’s common to see people install a wooden frame and a two-way mirror around the monitor, effectively creating a do-it-yourself smart mirror.

Downloading the Magic Mirror repository

Now that we’ve established how to set up our Raspberry Pi and familiarized ourselves with the Terminal, it’s time to download the Magic Mirror repository. In order to do this, you’ll have to clone the repository that is hosted on the popular website GitHub. GitHub is an online version control repository, basically, a place where the changes to computer files and code can be tracked and all workers on a particular project can come together to add the appropriate documentation. In line with the open source nature of this project, it’s very helpful for your future endeavors with this project. If you find that you have further questions, bug issues, or code to contribute, checking out their GitHub repository is the next and later step.

Now in terms of cloning the repository, using this phrasing is deliberate. To clone a repository means to not only download the current working copy of a project, but to also download every version of the project available. This is extremely useful for individuals who face problems with file corruption or server issues. So, moving into cloning the Magic Mirror repository, it’s fairly straightforward and we’ll get to it shortly. I’m having you walk through the manual installation of the Magic Mirror so that you have a better understanding of what is happening while interacting with the command line. I’ll show the alternate way later on in the text, but this builds some necessary skills for later on in this book. In turn, we have to install a few more packages before cloning into the repository in order to have the Magic Mirror run efficiently.

Installing Node.js

Node.js is an important aspect of the Magic Mirror setup as it creates the screen image with the specific modules on the monitor. It’s described as “an asynchronous event driven JavaScript runtime… designed to build scalable network applications” (about Node.js). While Raspbian, our operating system, does a timely job at staying updated, it behooves us to make sure that we have the latest version of Node.js in order to run our Magic Mirror program. We’re going to install the latest 64-bit ARM (known as Advanced Reduced Instruction Set Computer Machines) version for our Raspberry Pi. In order to install the latest version of Node.js, you’re going to execute the following steps:

  1. Make sure that you have an active Internet connection.
  2. Open up LXTerminal.
  3. In the Terminal, type the following:
wget http://node-arm.herokuapp.com/node_latest_armhf.deb
sudo dpkg –i node_latest_armhf.deb
  1. This was me telling the Pi to grab the most current version of Node.js and then switch to the root user in order to install the node package using dpkg, which is the Debian package management system.
  2. Wait for Node.js to download.
  3. Once the download has finished, double-check that you have the latest version by inputting node –v into the command line.

Installing Grunt

With some of the updates to the Magic Mirror program, I’ve found that it’s best to have the latest version of Grunt installed on your Pi as well. Grunt is basically a task manager and a build manager that integrates with Node.js. It has certain features that are helpful in the JavaScript environment, such as minification or the process of removing all unnecessary characters from source code without changing its functionality. On top of that, Grunt enables your program to reload as you make changes to your code during development. You’ll notice, when we start the Magic Mirror later on, that we’re going to call on Grunt usage with the npm start command. Grunt installation is very simple. We’re going to want to install Grunt’s command-line interface globally on the Pi. This way, we can readily call upon it when working from any directory:

sudo npm install –g grunt-cli

With Node.js and Grunt now downloaded, it’s time to finally clone into our repository:

  1. Make sure your Raspberry Pi is updated and upgraded. You can do this by typing sudo apt-get update && sudo apt-get upgrade.
  2. Clone the repository with git clone https://github.com/MichMich/MagicMirror ~/MagicMirror.
  3. This will download the directory containing the Magic Mirror files directly to your /home/pi folder.
  4. You’re going to enter the repository with cd ~/MagicMirror.
  5. You are then going to install and run the application using npm install && npm start.

It will take a second or two, but you will then see the default screen for your Magic Mirror pop up on your screen (Teeuw).

Working with the configuration file

Now that we have the Magic Mirror up and running, we have to personalize it. Consider where the Magic Mirror is going to be placed within your home. Are you going to be using it as a clock? Does it replace your bathroom mirror? Is this something that you’ve mounted near the front door so that you may scan some information as you leave for the day? All are excellent questions to consider and will mold how you choose which modules to include and which information should be highlighted. As you consider your options, take note of the default modules that are preinstalled with the application:

  • Clock: This displays the current date and time.
  • Calendar: This displays information from any public iCal calendar and can combine multiple calendars into one.
  • Current weather: This will display your chosen location’s weather information. It’s geared toward using the API from http://www.openweathermap.org/api.
  • Weather Forecast: Also using OpenWeatherMap, this will display the location’s forecast for the week.
  • News Feed: You can input news URLs of your choosing and the title of each news source, and this will scroll through the major headlines of the chosen news sources.
  • Compliments: This gives you the ability to randomize your own text content on the screen at a given the time of day: morning, afternoon, and evening.
  • Hello world: This places static text on your screen in a location of your choosing.
  • Alert: This module will display notifications from other modules.

As you can see, these working in tandem can create a very informative mirror for your everyday use. So, how do we actually customize? The customization process relies on the configuration file nestled in /MagicMirror/config. You’ll notice that when you move into the config directory, a file that you see listed is config.js.sample:

We have to make a copy of config.js.sample, and the easiest way to do that will be by making sure that you’re in the config directory and making a copy of the file:

cp config.js.sample config.js

So, any changes that you make to the config.js file will show up on the Magic Mirror screen. If you make an inexcusable error or find yourself needing to revert to the defaults entirely, you still have the sample copy to rely upon.

This is the sort of screen you will see with the default config.

Editing the configuration file

If you’re a complete novice to JavaScript, don’t worry too much about this process. Remember, the idea is to learn through trial and error and create a product that instills some pride. One way to build skills is to start editing and adding to the configuration file copy that you created in the previous section. The nice part about editing this file is that if your syntax is wrong or there’s a typo living somewhere in your document, the Magic Mirror will display a screen that alerts you to this problem. So there’s no harm in trying it out!

If you find it difficult to fix any problems or errors in the script, be mindful that there are browser-based JavaScript editors online that help you find the errors in your code. It comes down to a matter of copying and pasting, so I’d encourage you to turn to a website such as JSLint, found at http://www.jslint.com/. So, on to the configuration file as a whole:

/* Magic Mirror Config Sample
*
* By Michael Teeuw http://michaelteeuw.nl
* MIT Licensed.
*
* For more information how you can configurate this file
* See https://github.com/MichMich/MagicMirror#configuration
*
*/

var config = {
address: "localhost", // Address to listen on, can be:
// - "localhost", "127.0.0.1", "::1" to listen on loopback interface
// - another specific IPv4/6 to listen on a specific interface
// - "", "0.0.0.0", "::" to listen on any interface
// Default, when address config is left out, is "localhost"
port: 8080,
ipWhitelist: ["127.0.0.1", "::ffff:127.0.0.1", "::1"], // Set [] to allow all IP addresses
// or add a specific IPv4 of 192.168.1.5 :
// ["127.0.0.1", "::ffff:127.0.0.1", "::1", "::ffff:192.168.1.5"],
// or IPv4 range of 192.168.3.0 --> 192.168.3.15 use CIDR format :
// ["127.0.0.1", "::ffff:127.0.0.1", "::1", "::ffff:192.168.3.0/28"],

language: "en",
timeFormat: 24,
units: "metric",

modules: [
{
module: "alert",
},
{
module: "updatenotification",
position: "top_bar"
},
{
module: "clock",
position: "top_left"
},
{
module: "calendar",
header: "US Holidays",
position: "top_left",
config: {
calendars: [
{
symbol: "calendar-check-o ",
url: "webcal://www.calendarlabs.com/templates/ical/US-Holidays.ics"
}
]
}
},
{
module: "compliments",
position: "lower_third"
},
{
module: "currentweather",
position: "top_right",
config: {
location: "New York",
locationID: "", //ID from http://www.openweathermap.org/help/city_list.txt
appid: "YOUR_OPENWEATHER_API_KEY"
}
},
{
module: "weatherforecast",
position: "top_right",
header: "Weather Forecast",
config: {
location: "New York",
locationID: "5128581", //ID from http://www.openweathermap.org/help/city_list.txt
appid: "YOUR_OPENWEATHER_API_KEY"
}
},
{
module: "newsfeed",
position: "bottom_bar",
config: {
feeds: [
{
title: "New York Times",
url: "http://www.nytimes.com/services/xml/rss/nyt/HomePage.xml"
}
],
showSourceTitle: true,
showPublishDate: true
}
},
]

};

/*************** DO NOT EDIT THE LINE BELOW ***************/

While reprinted here, you can also access this file for editing by employing the use of the nano function in the command line. As always, make sure that you're in the configuration directory found within the Magic Mirror directory: /home/pi/MagicMirror/configuration. At this point, you want to tell the Pi that you wish to edit config.js. In order to do that, type sudo nano config.js into the command line. This will bring up the preceding file text on your screen, where you can easily move the cursor around to add and remove items.

In terms of observation, there are a few items to which I wish to call your attention. Toward the top of the script, you’ll notice that there are some initial customizable options, such as port, ipWhitelist, language, timeFormat, and units. Let’s explore each briefly:

  • port: Not to be confused with a USB port, this is regarded as the endpoint of information in an operating system. You can change the port address, but 8080 is the conventional address that you’ll see used somewhat ubiquitously as your personally hosted web server. Over your local network, it’s easily accessed and can be used to view your Magic Mirror in a browser, as opposed to the application view. As a side note, running the Magic Mirror on a local host would be useful if you wanted multiple browser displays showing the same information. Some museums and venues use this setup for guests.
  • ipWhitelist: If you’d like to remote into your Magic Mirror, you’ll have to add the IP address of the machine you’d like to use. With updates to the Magic Mirror happening frequently, I would suggest that you look to the active Magic Mirror community and its discussions in case there are any issues.
  • language: While setting to English, you also have the options of nl, ru, and fr, Dutch, Russian, and French, respectively.
  • timeFormat: You can change this from the 24-hour clock format to the 12-hour format by inputting 12 in this space.
  • units: While setting to metric, you can replace this with imperial.

After going through these preferential settings, you’ll notice that the body of the script deals directly with the modules that are going to be displayed on your screen. You’ll notice a pattern with the curly brackets, as they enclose each module. There is a standardization to how each module is set up, which may be helpful if you find yourself puzzled about how to incorporate preferences and variables:

{
module: 'module name',
position: 'position',
header: 'optional header',
config: {
extra option: 'value'
}
},

Understanding the module

So, let’s take the compliments module as our example working piece. If you pass your eyes back over the config.js file, you’ll notice that the compliments module is nestled fifth from the top. You’ll notice that the only information in the config.js file for the compliments module is its placement: lower third. How does the compliments module know what information to display? Where is the revolving text coming from? The config.js file is using and calling up the information stored in the compliments directory, found in /home/pi/MagicMirror/defaults/compliments, specifically, compliments.js. Logically, we would need to edit the compliments.js file in order to change the content of the compliments module. Accordingly, we must understand that the config.js file literally deals with the spacing and configuration of the Magic Mirror display. Moving forward, let’s take a look at a portion of the compliments.js file after you’ve navigated to the compliments directory:

cd /home/pi/MagicMirror/defaults/compliments
sudo nano compliments.js

While looking at this file, we see the most important content aspects—anytime, morning, afternoon, and evening, toward the top. As you can guess, these compliments or text portions roll through the screen given the appropriate times of the day. Consider what content you would like to change or add and play around with modifying it. Also, make note that later in the compliments file, you have the ability to modify the hours dedicated to morning and afternoon, the leftover hours being dedicated to the evening:

complimentArray: function() {
var hour = moment().hour();
var compliments;

if (hour >= 3 && hour < 12 && this.config.compliments.hasOwnProperty("morning")) {
compliments = this.config.compliments.morning.slice(0);
} else if (hour >= 12 && hour < 17 && this.config.compliments.hasOwnProperty("afternoon")) {
compliments = this.config.compliments.afternoon.slice(0);
} else if(this.config.compliments.hasOwnProperty("evening")) {
compliments = this.config.compliments.evening.slice(0);
}
if (typeof compliments === "undefined") {
compliments = new Array();
}
if (this.currentWeatherType in this.config.compliments) {
compliments.push.apply(compliments, this.config.compliments[this.currentWeatherType]);
}
compliments.push.apply(compliments, this.config.compliments.anytime);
return compliments;
},

Once you’ve played around with modifying, understand that this process is replicated for the majority of modules in this program. I’d recommend that you take the time to look through the default folders and see what else you can change. If you’re worried about mistakes or editing a file in an error, make a copy of the original file, rename it, and leave it so that you have a reference point or a file to revert to.

Installing third-party modules

While the Magic Mirror comes with default modules, there are industrious Internet folk out there creating new, open source modules for download and addition by going to the third-party module portion of the Magic Mirror GitHub website, https://github.com/MichMich/MagicMirror/wiki/MagicMirror%C2%B2-Modules#3rd-party-modules. While extensive to list, you’ll note that there are modules for Twitter, Instagram, NFL scores, and Amazon’s Alexa, to name a few. These come with varying degrees of skill needed to set up, so it’s suggested that you assess which seems to be the best to try and then work through the installation and setup steps. Importantly, when installing a third-party module, you’re going to clone the repository into the Magic Mirror modules folder. Your steps would involve the following:

  1. Navigate to the Magic Mirror modules folder.
  2. Determine the URL of the GitHub repository you wish to clone.
  3. Clone the repository using the steps mentioned previously in the chapter.

Here is an example of what your mirror may look like once you place a two way mirror on the screen plugged into your Raspberry Pi 3:

You have been reading a chapter from
Raspberry Pi 3 Home Automation Projects
Published in: Nov 2017 Publisher: Packt ISBN-13: 9781783283873
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime