DIY WiFi Smartbulb Classroom Sound Meter

This is an exciting new project I’ve been working on to use off-the-shelf smart lightbulbs to make an inexpensive and automatic classroom management gadget. Using a bit of Node I was able to get the noise level of a classroom and translate it into a color for a connected smart lightbulb, from green to red as the classroom gets louder! Inspired by the ‘traffic light’ noise warning gadgets I see in classrooms, this one is fully automatic. There are no switches to throw- just set the maximum volume in the free software and the lightbulb will change color on its own!

screenshot-2
Screenshot of the GUI. The program is an Electron application, and I have applied a material design stylesheet.

The software can be downloaded for free for Windows PCs here!

Works with MagicHome brand smart lightbulbs, such as these which are known to work:

MagicLight WiFi Smart Light Bulb, 2nd Generation Dimmable Multicolor A19 E26 Household LED Bulb

MagicLight Smart WiFi Alexa Light Bulb, A19 7w (60w Equivalent)

As always, this program is open source! Click here to view the code on GitHub!

Can’t connect your IoT devices in the classroom? Try a Travel Router!

THE PROBLEM

It can be difficult or dangerous to connect internet of things (IoT) gadgets like sensors, smart light bulbs, switches, digital assistants, etc. to campus WiFi networks. Your information technology department may have instituted restrictions on connecting these devices to their network, a landing page may make connecting impossible, or no guest network may exist. Additionally, it is good practice to keep IoT gadgets on their own separate network for security. The FBI has made several recommendations including using a separate network for operating IoT gadgets safely.

Travel routers offer a convenient way to set up this separate network inexpensively and with portable equipment. Unlike your home router or the router in your workplace these routers are small and low power, and can even be run off a USB port on your computer! The range of these devices vary, but generally will cover a single room.

THE SOLUTION

Microrouter Diagram

Introducing the GL.iNet GL-USB150 Microuter! This handy little USB microrouter creates a small, easy to set-up WiFi network around your computer. When connected to your laptop, it will appear as a second network connection, letting you access all of your IoT gadgets as well as your campus internet. There are many travel routers out there that may better suit your needs, but this one is small, inexpensive, and has worked for me in the past. It is easy to use and portable.

Setup

  1. Plug the microrouter into your computer
  2. In your web browser, go to http://192.168.8.1 to complete setup (Documentation here)
  3. If your devices will need internet access, you can connect your router to the campus internet itself using the connect tool on the main page.
  4. Your router is now broadcasting. Connect your IoT gadgets to the network using their respective apps. You should see a network that starts with the words “GL-USB150…”. Your devices should have no problem connecting to this new network instead of the campus network.
  5. Connect your tablet or phone to your new network when you want to control the devices with their apps. Your computer will always be connected to this network as well as the campus network, requiring no reconnection. It will treat the new network as a second network connection.

Potential Issues

  • The GL-USB150 router is a 2.4 GHz device. If you plan on connecting it to the campus WiFi because some of your devices require internet access (note that many devices like switches, light bulbs, etc. do not need internet access, they can be operated on a network without an internet connection) you should verify it is not a newer 5 GHz network. Note that some devices, like Amazon Echo devices, do need internet access so putting them onto a network like this without setting up an internet connection will not work.
  • Some IT policies forbid you from running your own networking equipment.

CONCLUSION

When volunteering in schools I have run into this problem before- a teacher wants to use a cool new gadget but it just won’t connect to the WiFi. This workaround as worked for me, and I hope it works for you!

DIY ‘Ghost Box’ for Halloween 2019!

This is a DIY Ghost Box like the Ovilus ghost hunting device. While I don’t believe in ghosts, I do think ghost hunting gear is fascinating. This box chooses words out of a 1000 word dictionary based on magnetic field and temperature changes. The code is available for free on GitHub: https://github.com/kevinl95/ghostbox

Electronics:
1x Adafruit Feather M4 Express (If substituting, make sure you either buy a board with a DAC for the speaker or build one)
1x Adafruit 9-DOF Accel/Mag/Gyro+Temp Breakout Board – LSM9DS0
1x Adafruit Illuminated Toggle Switch with Cover – Green
1x Adafruit Thin Plastic Speaker w/Wires – 8 ohm 0.25W
1x Adafruit Lithium Ion Battery – 3.7v 2000mAh

CAD and STL files can be accessed from the Thingiverse project page!

Getting a ‘Feels Like’ Temperature when transitioning away from the Weather Underground API

IBM has made the disappointing decision to retire the Weather Underground API effective 12/31, leaving many developers scrambling due to the abruptness of this decision and the complete lack of roadmap or guidance as to how to transition to a replacement so that their applications will work on January 1st.

One key element of the Weather Underground API that my popular tutorial for making an Alexa Skill makes use of is the ‘feels-like’ temperature. When updating this tutorial due to the bad news I chose to transition this tutorial to the OpenWeatherMaps API, which offers a free tier like the Weather Underground API used to that allows for up to 60 requests per minute and the current weather.

While it does not offer a ‘feels-like’ temperature, this can be easily calculated by simply factoring in wind chill to the temperature you report. This means you do not need to use OpenWeatherMaps- you can really use any API that gives you a current temperature and wind speed! It really is as simple as this:

 

The formula in the above code is to calculate a temperature with windchill using US Customary units:

Wind Chill = 35.74 + 0.6215T – 35.75(V^0.16) + 0.4275T(V^0.16) (Courtesy of MentalFloss)

where T is a temperature in Fahrenheit and V is a wind speed in MPH. You should be able to find a corresponding formula for metric online.

I also went ahead and rounded my ‘feels like’ temperature to one decimal place, to make it easier to read (or for a voice assistant to read out loud, which is how I eventually used this code).

I hope this helps others as they transition to other weather APIs as Weather Underground winds down. Its developer community will be missed!

Making your first Capsule for Samsung Bixby – An Exercise in Teaching your Phone to Listen

 

Today Samsung made the Bixby Developer Studio available for download and use so that developers can start building capsules to publish on their marketplace starting in 2019. I am an early adopter of the new Bixby and wanted to share how to build a simple capsule using the new developer kit as well as share my experience with using the new platform. Readers of this blog know that I have made and published Skills for Amazon’s Alexa and published tutorials on how you can develop for that platform. Similarly this writeup will focus on a minimal application that will help you get started with the features of Bixby’s impressive development tools.

Bixby is a wonderful platform to develop for and it has top-notch development tools. Building software for Bixby is a lot like teaching someone a new skill. It uses natural language model training so you can show Bixby what parts of user phrases are important and it uses the idea of concepts to define Bixby’s understanding of what capability you are giving it. These concepts will be discussed in detail below.

Today we will be making a capsule to generate passwords made up of a random string of words, inspired by XKCD’s Password Strength comic. We will be taking advantage of Bixby’s visual interface to make a password users can easily remember as well as easily copy and use for their accounts. The XKCD algorithm sticks random, memorable words together so that passwords are complex but can also be easily recalled by the user. They also are higher entropy than a random string of characters and numbers, making them harder to crack my many brute-force methods. After giving the comic a quick look, read on.

As always, you can download and view the code on my GitHub!

THE PROBLEM

We want to build a Bixby capsule that can generate memorable passwords for users. These passwords should be of a user-specified length.

The overall requirements are:

  • Generates a password using regular English words
  • Takes in a user’s specified length
  • Displays the password graphically for copying
  • Displays a calculation of the entropy of the password so the user knows how good the password is.

THE SOLUTION

You should now have Bixby Studio installed on your system. As of writing it is available for Windows and macOS.

Create a new project by clicking File>New Capsule.

The first bit of code we will focus on is the generator.js file. This is where we define our entry point and what we are going to return.

Notice how we export the function generate- this is the function where I generate everything we need for the response you see in the screenshot above. We take our wordlist dictionary file (how to get that will be discussed shortly), we build our password using a user-specified length called numWords, and we calculate the entropy of the password. We then return a result we can parse into a nice, visual response like in the screenshot.

Whew, there’s a lot going on in here though! Let’s start with the wordlist. This is a JSON-formatted list of common English words I found searching for open-source corpora. Why JSON? As you might have surmised from the above code snippet, Bixby capsules are written in JavaScript! Importing this data as JSON makes it very easy to loop through and use, as you can see in my generate function. I stored this in a directory called lib but you can call it whatever you please. Just be sure to update the path in the generator!

Next, we need to discuss how we get numWords. This is the user-input. We want the user to say ‘Make me a password with three words’ and Bixby needs to know how to do that.

In the resources directory you will find endpoints.bxb. The actions your capsule can take are called endpoints. Let’s define one for generating a password:

Let’s look at what we have here: We have authorization set to none because this endpoint is public and available to any user without authorization. We have specified an action endpoint for our generate function as defined in the generator.js snippet above and we have told Bixby that the input for this endpoint is numWords. We also tell it what file it will find the definition for this endpoint in- generator.js.

Now that Bixby has an available action in the form of the endpoint, we get to the really interesting stuff- teaching Bixby what everything in our capsule means. The way we do this is via a model. In the model directory we have actions and concepts. These make up Bixby’s understanding of what your capsule can do, and we just need to write some high-level markup to make this work. Let’s start with the action our capsule is going to have- generating passwords. This will inform what concepts Bixby needs to have definitions for so that we can move on to training our natural language model.

Above is the generator.model.bxb action file. You will find it in my action directory. What does this do? Read through the comments carefully. It defines the actions Bixby will take when running this capsule, and it covers all our bases regarding various user inputs! We tell it our action is to run our generate function. We tell it to collect numWords, and we tell it that numWords is of the numWords concept type which we will define shortly. We tell Bixby that there can be at most one numWords (so that we ignore other numbers in the user’s invocation) and we tell Bixby that this value is required. If Bixby cannot find a number in the invocation to use, we define a default initialization with four words- the same as our XKCD comic! We then do some validation in the event we find a number in the user’s invocation. If numWords is 0 or less, we want to display some text telling the user that you cannot have a password that is negative in length (duh, but the bulk of software development is anticipating stupid). Finally we tell Bixby what our result is going to be- an instance of our PasswordResult concept, which will be of the type Calculation. This is a type Bixby provides for a result that it needs to compute or otherwise derive. Let’s get started defining what these concepts are.

If you are following along in the repo, look at the numWords concept.

This is a good minimal example of a Bixby concept. These are the variables that are key to our capsule working. You can think of them as teaching Bixby a new idea, slowly building for it the picture of what you are trying to achieve. We tell Bixby that NumWords is an integer (we don’t want fractional words). We also give a brief description of what this has to do with our capsule. For NumWords this is obvious- it is the number of words in the password.

Password is almost the same except this concept is given the ‘name’ type since we need an output string. We describe it as the output password. Entropy is similar- we describe it as the approximate bits of ‘randomness’ in our password and give it the integer type since it will be a number we calculate. Length, predictably, is an integer that represents the length in words for our password. This is utilized in the entropy calculation, which taking the formula from the comic is taking two to the power of the number of words and then dividing for the number of attempts to brute force the password you could make if your computer could make 1000 attempts per second for a year. This yields an estimation of the number of years the password would take to crack in these circumstances. Finally Years is given the integer type and described as the number of years simple brute forcing would take to crack this password- it is also part of the entropy calculation we display at the bottom of our result as you can see in the above screenshot.

The most complicate concept is our PasswordResult:

It has the type Structure because it contains multiple properties- namely every concept we have just defined. We give these properties types- I just made these the same as the property name for simplicity but they can be used in more complicated capsules to link properties together with a descriptive type. We again describe each property and what it does, tell Bixby if the property is required, and for each tell Bixby that there can be at most one value for each. This result, as you may recall from the generate method, is what we will use to generate our visual response on the screen of the device. We have now explicitly told Bixby everything there is to know about how our capsule is going to work! It knows every concept and every result we are going to want. We now can teach Bixby how to handle speech.

Click training in the resources/en directory.

Screen Shot 2018-11-07 at 7.11.44 PM

You will see a list of training examples I have provided the natural language model. We are effectively training Bixby to understand how to parse user phrases and turn them into useful input for our capsule. This is an application of machine learning! Notice the examples I have provided. I have made one: ‘generate a password for me’ with no numbers in it- this is to provide an example where Bixby should use our default input of four words from above, like the XKCD comic. I also provide numerous examples with varying numbers of words asking Bixby to generate a password in various ways. Notice how I have clicked on and highlighted the number in each training phrase and I have labeled this value as numWords! You will do this for each input your capsule needs- the more examples the better. Bixby will use the labels and examples you provide to teach itself that when something sounds similar to your examples Bixby is being asked to open your capsule and feed the data that is similar to the labeled phrases you gave it to the capsule as input. Bixby is learning, so make sure to spend plenty of time here to make sure Bixby really gets it! Compiling the model will make Bixby learn each of your examples and you can view what Bixby’s output for your examples would be so you can be sure that Bixby has not mis-learned how to handle your examples. A well-trained model will make your users happier and your capsule easier to use. This is my favorite part of the Bixby developer tools- it is very intuitive and fun to use, and it offers a look for machine learning enthusiasts into the underlying technologies behind Bixby. This is a defining attribute of the platform for me- it feels much more flexible than Alexa, which as a developer seems to encourage a more robotic and specific interface for its skills than the more flexible Bixby interfaces for capsules.

With your model trained and your concepts laid out, the last thing to do is to specify how Bixby should display our output. This is done with dialogs and layouts.

Dialogs define for Bixby’s interface the concepts (inputs) and the results. Therefore for each input you need there will be a dialog and for each result there will be a dialog.

NumWords therefore gets a dialog like so:

This is pretty bare-bones: We define a concept dialog (input dialog), tell it to look for NumWords (like in our training!) and we provide some template text for this type if we wanted to display something related to this input (in my project I ended up not using it).

The Password Result Dialog defines the dialog for our result. This one is more important for this project as it will populate our layout.

We define an output (result) dialog, have it match this time for our PasswordResult concept (passing in the output from calling generate with our numWords result) and then we tell Bixby what to write on the screen with the template text: Notice that this is the first bit of text in the above screenshot that appears when Bixby is displaying a result telling the user what it did for them!

The layouts for the visual part of the display (like this one, PasswordResult.layout.bml) look a lot like HTML! There are many documented UI widgets you can use such as pictures, hyperlinks, cards, and more. Here you can see we use a card to display the actual password, making it wrap onto the next line for long passwords and making them easy to copy. Down below in a div tag we display the password entropy. This is calculated using the formula from the XKCD comic, as described above. Finally we hyperlink to the comic that inspired this project as a way of giving credit.

A few more example passwords are shown below:

You can try it out for yourself in Bixby Studio! Simply click the icon that looks like a phone on the left hand side of the screen to open the Simulator, giving you an idea of what your capsule will look like on an actual Samsung device when the marketplace opens in a few months.

SHARING THE SOLUTION

This project can be found in its entirety on my GitHub! I hope this very early tutorial can help developers make their first steps into developing for Bixby, which I think has some very compelling development tools and technology behind it.

How to download a YouTube video for Seesaw

Have you ever wanted to download a YouTube video to share elsewhere but found that every ‘YouTube Downloader’ on the internet is an adware-filled, slow-to-load piece of junk? This is especially problematic when you are trying to get video content to your students- most of the time you cannot directly link to YouTube on a school network connection as it will be blocked, leaving your only option to download the video and re-share it on a platform like Seesaw, a popular platform for student engagement. So how can you get the raw video file to share without getting your computer infected? I have designed a simple desktop application that downloads YouTube videos and I am offering it for free to download! It is available for MacOS and Windows. Best of all it’s a portable app- meaning no installer and therefore no need for an administrator password to use on your school computer!

If you are interested in how I developed this program, read on.

THE PROBLEM

YouTube download websites are filled with adware, malware, deceiving links, and often inappropriate ads. Educators need to be able to download YouTube videos to get around school content filters. They need to be able to use a program that can also evade roadblocks like not being able to install software on a school-issued computer.

THE SOLUTION

screenshot
The Windows version of the application

The solution was to develop a desktop application (ensuring the longevity of the project as there would be no need to pay for hosting a website or risking my web application getting blocked by a content filter). I also wanted to write this application once and deploy to my two target platforms – Mac and Windows. There are various libraries for downloading YouTube videos simply – I figure a lot of the scammy websites are making use of the open-source ytdl-core or similar JavaScript libraries to download their videos and quickly deploy new websites. I wanted to use something similar as these libraries are easy to use, well-supported, and cross-platform. The solution for all of my problems was to build my app using Electron, which lets you build cross-platform apps using HTML, CSS, and JavaScript. I could build a website using ytdl-core to download videos using the same technology as the sites people are being driven to by Google and then make it a desktop application. Then, using the exact same code for both platforms, I could then deploy to Windows and Mac! And that’s exactly what I did- what you see above in these screenshots is literally a simple website using jQuery, Bootstrap, and ytdl-core that takes in the YouTube link the user pastes in the box, uses regex to check that the link is a properly formatted YouTube link, and then opens a save prompt to save the video to the user’s computer! The save prompt is one of the neat elements of the Electron API that you can just use and have it work one each platform, pulling up a native save dialog and letting me configure it to ensure the user can only save MP4 files, for example, as that is the file format Seesaw accepts. The open-source Electron Packager then lets me bundle all of my dependencies together and create a Windows and Mac application bundle. These bundles include everything needed to run the application in exactly the spot the application needs it, meaning there is no installer to run and therefore it can run without administrator access on your computer! The whole ecosystem let me hack this together very quickly with almost no friction between any of the tools.

ytdl-core lets me ensure that we automatically grab the highest-quality version of the video and download it in MP4 format, making sure everything is as simple as possible to go from video to Seesaw fast, saving teachers time. This all happens in the background – the goal was to make a tool that takes minimal thought to use. Just grab the video your students need, and paste the link!

SHARING THE SOLUTION

This application is completely open-source. You can view it on GitHub here! This also serves a project homepage you can share with your friends and colleagues as it features download buttons for both Mac and Windows. It is also where you should go to get the most up-to-date versions of the software- as I improve it and make bug fixes the links below will not be updated, but they will always get you the first release.

V1.0 for Windows can be downloaded here directly.

V1.0 for MacOS can be downloaded here directly.

 

A scrolling LED Display for your Google Calendar!

My brother had the awesome idea to stay organized this school year with a scrolling LED display that would read the next five tasks off a Google Calendar. This is the exciting end result! The LED display we used unfortunately ran only proprietary software called PowerLed, giving me no way to programmatically set the text the screen was displaying and instead requiring each line be manually entered (like some kind of neanderthal). Fortunately Python has tools for automating actions in even the gnarliest GUI programs, so I wrote up this guide about how I managed to make this dumb device smart!

THE PROBLEM

It’s <current year> and manufacturers are still shipping hardware with awful proprietary software and no way for the end user to tinker with it. Additionally it is not web-friendly and all information has to be edited by hand.

The specific sign I worked with was this one although many signs originating in Asia ship with the same PowerLed software, so this guide should help you out! I made use of the WiFi interface, so if your sign does not have one you should check if it has a serial interface instead and make a few modifications to my program (remove the Wifi stuff, have the program click the button to send the configuration over USB for example).

THE SOLUTION

(TL;DR here is the code!)

There are a number of tools that let you click through GUI programs and automate tasks with Python, but today I am going to focus on pywinauto, a popular set of modules for automating tasks in Windows GUI programs. This is appropriate because as far as I can tell my sign only came with a Windows version of the software (although there are mobile apps that work with it supposedly). Pywinauto works by opening a program at a specified path and then navigating down menus it can see. For example, I can tell it to send my configuration by telling it to click a certain member of the Tools menu at the top of the screen: ‘window.menu_select(“Tools(T)->Send All”)’. It’s that easy! Those names were copied directly from the GUI itself.

I made use of the Google Calendar API which lets me programmatically pull down information from a Google Calendar. At the time of writing Google gives a generous one million queries per day which I cannot imagine one person would ever be able to exceed. To be safe though, my code updates the sign’s text every three minutes (although this can be changed at the top of main.py). The program I wrote pulls down the next five events on your calendar and processes them to be displayed by the sign.

How does this all work?

  • PowerLed uses ledprj files which are essentially just XML files. I made my own template with placeholder text (‘REPLACE1’, ‘REPLACE2’, etc.) and saved this template alongside my Python script. This template let me play with scroll speed, font size, and other settings using the PowerLed software and trial and error with my display. To automate updating the template with Python, I simply read in this template file and do a find/replace for ‘REPLACE1’ and so forth with the five events I pulled from Google Calendar. When PowerLed reads this file, these strings are sent instead!
  • The LED sign broadcasts its own WiFI network that I must connect to in order to update the device. I use subprocess calls to netsh to drop off my WiFi and then connect to the display.
  • I use pywinauto to open PowerLed, which I have already pointed at my LEDprj file, and connect to the device. I then automated the process of pressing the ‘send’ button to update the display. Once updated, pywinauto automatically closes PowerLed.
  • The project then waits three minutes and pulls down the next five events again, updates the sign, and so on until the program is stopped.

By noticing that the LEDPrj files were really just XML files I saved a great deal of time reverse engineering how I can get Python to update this sign. While there is no API or command line interface for the software, pywinauto let me quickly get the computer updating the sign itself.

Now I am sure you’re thinking ‘This is all fine and good, but do I need to let this program run forever, popping open this PowerLed thing every three minutes?’ – the answer is yes. But there is a solution! Upcycle an old laptop (68% of Americans have an unwanted computer in their home) or make use of a cheap Intel Compute Stick or similar device (make sure it runs Windows, the cheapest ones run Linux). I used an inexpensive Windows compute stick with an Intel Atom processor inside that more than handily can run this program on loop forever.

How do you get this set up for yourself? Head on over to the Git repo and check out my README, it’ll fill you in! The gist is to clone the repository, follow Google’s procedure to enable the Calendar API and get a credentials file, change the values in the program so that it knows what time zone you are in and what networks it needs to connect to (I don’t pass credentials, the program expects you to have connected to your sign and your home network before) and then give it a try!

TROUBLESHOOTING

  • I assume you have PowerLed installed and you made sure the path in the program is pointed at where you installed it
  • I assume you have connected to your sign and your home network before
  • I assume that you have loaded display.ledprj in PowerLed and then exited the program so that it will load next time you open PowerLed
  • I assume you are running Windows and that you have installed Python 3

SHARING THE SOLUTION

My code and instructions can be found here.

Here are the exact products I used:

How to extract PDF file attachments using Python and PyPDF2

Tl;dr: Cut and paste the function I wrote here.

This is a quick technical writeup to hopefully answer a question I’ve seen posted a few times around StackOverflow and the issue trackers of various Python PDF libraries. This is especially handy for those of you who don’t want to dive through the PDF32000 to figure out how Adobe wants us to handle attachments.

PyPDF2 makes working with PDFs easy, but you may have noticed that it only has an addAttachment() function, similar to many other PDF libraries I tried. How do we extract attachments so that we can work with them? Embedding files in PDFs is very common and it would be nice to be able to interact with these objects, like we can with form fields and other things you might find in PDF files.

Fortunately the building blocks how how to do this are already available in the PdfFileReader class!  We just need to stitch them together:

  1. Read the PDF file using PdfFileReader from PyPDF2
  2. Decrypt the PDF if necessary (required, you can’t get to the embedded files without doing this)
  3. Retrieve the file catalog by retrieving the file trailer (reader.trailer[‘/root’])
  4. Navigate in the dictionary this returns to ‘/EmbeddedFiles’
  5. Loop through the list of files that are found there
  6. When we get to an IndirectObject, we have our file parameters. We call getObject() to return the parameters dictionary, then navigate to ‘/F’ where our file data is stored as yet another IndirectObject. Here we simply call getData() and get a byte string back. This can then be written to a destination file or processed however you please!

As always it’s better to show the code, so here’s a proof of concept script:

Easy, just not immediately intuitive when you want to do this fast! I created pull request to hopefully get this function added as a method for the PdfFileReader class.