Phidgets on the Net With Raspberry Pi
by VhsSymptom in Circuits > Raspberry Pi
901 Views, 5 Favorites, 0 Comments
Phidgets on the Net With Raspberry Pi
As technology today becomes more and more advanced, so-called "smart" devices are on the rise everywhere. From TVs to Fridges, and everything in between our life is more reliant on technology than ever. That being said, needing one app to control your smart lights, another to control your thermostat and so on gets annoying, not to mention the security risk if that cheap LED strip you bought off amazon is running less than secure firmware.
So what if you could help centralize at least some of your smart home (or classroom) needs while improving your security and allowing your devices to be accessed anywhere on your local network? Well in this Instructable I will be going over how you can set up and run your own webserver to control your Phidgets with the help of a Raspberry Pi. I will be using a Power Plug Phidget to turn on and off a light remotely as an example, but you could use any Phidget device you want to with some slight changes to the code.
Supplies
- Raspberry Pi
- Power Plug Phidget (PSU1000_0)
- VINT Hub (HUB0000_0)
- VINT Cable
- USB Type-A to Mini-B
Getting Your Raspberry Pi Ready
For this tutorial, I will assume that you have already installed Raspberry Pi OS and have access to your Pi, but if you don't there is a great guide on remote access on the Raspberry Pi official website which can be found here.
Once you are logged into your Pi we will need to install a few additional libraries. Usually, we would install the Phidget22Native package, but since we need a web server and a javascript API we will be installing the phidget22wwwjs library. The instructions below are current to the article, but you can also find them over at the Phidgets website here.
To start, open a terminal and copy in the following:
curl -fsSL https://www.phidgets.com/downloads/setup_linux | sudo -E bash - sudo apt-get install -y libphidget22 phidget22wwwjs phidget22networkserver
Please note that you will need to enter the sudo password, which by default should be raspberry on Raspberry Pi OS. Now you should have a webserver hosted at your Pi's local IP address. Navigating to your Pi's IP address which in my case is 192.168.1.100:8080 should give you the test page for the Phidgets webserver.
Connecting Phidgets to the RPi
Now that our Pi is configured we will need to connect our Phidgets. Start by connecting your Phidgets Plug to the VINT Hub Port 0 using a VINT Cable, and connect the VINT Hub to your Raspberry Pi using a USB Type-A to Mini-B cable. It's important that you connect it the same way as shown if you are going to use the code provided below, as otherwise the plug will not turn on and off.
With that done you will need to provide power to the Raspberry Pi once it's in its final location. For that I just used a small mains to USB wall plug, and then a Type-A to Micro-B cable.
Setting Up Our Webpage
Now that we have our Raspberry Pi set up, and the default webpage is up, we need to write our own. For the purpose of this tutorial, I have a Power Plug Phidget connected to a VINT Hub, which is plugged into my Raspberry Pi. With this in mind I like to build a sort of flowchart to figure out what I need my program to do. First things first we will need to either make an index.html file on our local computer, or open the one provided.
I chose to start with a new file, but you can just copy the contents of the included file under this step into the index.html file in your www directory if you wish. Now that we have our file open it needs some boilerplate HTML. Start by adding a head and a body like so:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> </head> <body onload="connectPhidgets()"> </body> </html>
Note that the body tag will run the function connectPhidgets(), this will be used later to connect our Phidgets. First though we need to add some tags inside the head tags. To start, we will give the page a name which in my case was Power Plug, but you can name it whatever you like. Then we need to link the Phidgets libraries stored locally on the Pi. When all is said and done your head tag should look something like the following:
<head> <meta charset="utf-8"> <title>Power Plug</title> <script src="sha256.min.js"></script> <script src="phidget22.min.js"></script> </head>
Now we need to write our connect function, and our on and off functions. To do this we will need to create a <script> tag in between our head and body tags. That will look something like this:
<script> function connectPhidgets() { var local = location.hostname; // Get localhost ip/hostname var conn = new phidget22.Connection(8080, local); conn.connect().then(startSchedule()); } var powerPlug = new phidget22.DigitalOutput(); var setOnTime = 8; var setOffTime = 16; var dt = new Date(); </script>
I also set some extra variables that we will need for later, including the Power Plug Phidget, the on and off time (with a default value of 8), and the Date() function that will grab the current time from the user's browser in 24-hour format.
Now you may notice that after we connect our Phidgets we call a function startSchedule(), so lets make it. It will need to be an async function to let us sleep it so that it doesn't hold up the browser. Inside we will define the connection to the Phidget Plug as it will be the second function called after loading. It will look something like the following:
async function startSchedule() { powerPlug.setHubPort(0); powerPlug.setIsHubPortDevice(true); powerPlug.open(); while(true) { console.log(dt.getHours()); // sleep for 5 mins, then check if within schedule await new Promise(x => setTimeout(x, 300000)); // if within schedule, keep plug on, else turn it off if (dt.getHours() >= setOnTime && dt.getHours() < setOffTime) { // turn on powerPlug.setState(true); } else { // turn off powerPlug.setState(false); } } }
Make sure that your Phidgets Plug is connected to port 0 or else it won't be found. As you can see inside the if statement we simply check if the current time is within the set schedule or not, and then enable or disable the plug using the setState() command.
Add User Input
Now that we have a base index.txt file set up everything should run, but it will be stuck to a schedule of between 8 am and 8 pm in 24hr time. Now we will add the functionality to not only change those times, but manually turn on and off the plug just in case you need it. To start, we will add a few extra functions inside the <script> tags.
First will be a simple on and off function that will look something like the following:
// When button is pressed, turn on light function turnOn() { powerPlug.setState(true); console.log("Plug is set to on by user"); } // When button is pressed, turn Off light function turnOff() { powerPlug.setState(false); console.log("Plug set to off by user"); }
(Please note that the console.log() lines are not necessary, but I chose to include them for the sake of debugging!)
Now we need a function that will update the schedule based on user input. To start we need a function in our <script> tags that will get an element from the web page. On the web page I chose to use a select box, as although the input box has support for numbers, the select box is more in line with what you would expect to see, and will only give you the options which are pre-defined. That said the function will look as follows:
function updateTime() { // Get set on time from selection box var onTime = document.getElementById("onTime"); setOnTime = onTime.options[onTime.selectedIndex].value; // Get set off time from selection box var offTime = document.getElementById("offTime"); setOffTime = offTime.options[offTime.selectedIndex].value; console.log("Schedule updated to: " + setOnTime + "-" + setOffTime); }
As you can see it will simply grab the selected input from our yet to be defined select boxes and change the variable in the schedule. That means that when the schedule function we defined earlier cycles through its sleep timer and checks the current time against the schedule it will be using our updated values.
HTML Time
Now that we have written out all our needed functions, we can get started on our HTML <body> tags. To start we are going to make two <div> tags, one which will contain our schedule and the other which will contain our on and off buttons.
<body onload="connectPhidgets()"> <div> </div> <div> <button onclick="turnOn()">Turn On Plug</button> <button onclick="turnOff()">Turn Off Plug</button> </div> </body>
As you can see the bottom <div> has two buttons, one to turn on and one to turn off the plug which will simply call our turnOn() and off functions respectively. Now for the top div we need to add our <select> tags, as well as labels, and finally, a submit button:
<body onload="connectPhidgets()"> <div> <label for="onTime">Turn On Time</label> <select name="onTime" id="onTime"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <...> <option value="22">22</option> <option value="23">23</option> </select> <label for="offTime">Turn Off Time</label> <select name="offTime" id="offTime"> <option value="0">0</option> <...> <option value="23">23</option> </select> <button onclick="updateTime()">Update Schedule</button> </div> <div> <button onclick="turnOn()">Turn On Plug</button> <button onclick="turnOff()">Turn Off Plug</button> </div> </body>
Please note that the <...> is in place of the lines which count from value=0 to value=23. They are included in the example code below. Finally, our submit button will call our updateTime() function, neatly tying together everything that we wrote in our script tag.
With that done, our index.html file is complete. I have included my fully written out example below so that you can either copy over its contents to the index.html file in Step 6, or simply remove the .txt file extension and place it in the directory in Step 6.
Downloads
Hosting Our Webpage on the Server
When we installed the network server we get a few new files automatically created for us. They will all be located at /var/phidgets/www so start by typing or copying the following into your terminal on your Raspberry Pi:
cd /var/phidgets/www; ls
You should see a listing of files come across your screen, and the one we want is index.html. Now you can either copy over the contents of your index.html file, or the contents of the one provided in Step 5. Then, when we navigate to our Raspberry Pi's address we should see our new web page. Finally, clicking the on and off buttons should turn on and off your plug, and updating the schedule should allow you to set a custom time for your plug to turn on and off automatically.
Conclusion
While it may not be the nicest webpage out there, it is yours! It's also purely functional, with no extra bloat, and no relying on third-party hosting services. If you have some experience with CSS I encourage you to try your hand and make the website look better, but it is beyond the scope of this Instructable.
I really appreciate you taking the time to read through and follow along with this guide, I hope you learned something new, and enjoy controlling your Phidgets over the web.