Smart-home data
Process your smarthome sensor data
HOME ASSISTANT
Matt Holder investigates how to take data from an API and display it in a GUI, using Python and Home Assistant.
Part Two!
Don’t miss next issue, subscribe on page 16!
OUR EXPERT
Matt Holder is an IT professional of 15 years, Linux user for over 20 years, user of plenty of home automation gear and selfprofessed geek.
QUICK TIP
The complete code listing can be downloaded from https://github.com/mattmole/LXF308-309-API-GUI.
This article is the second of a three-part series, where we are working on the program that we started last month. Our aim is to pull data from the Home Assistant API and then render it on screen in a GUI. We’ve split the program into two and last month we wrote the library that interacts with the API. This time, we are beginning to write the GUI portion and then use the library to authenticate with the API and grab the data.
So, let’s discuss a few of the basics. The Qt library has been chosen for this project, partly because it is cross-platform and has a freely licensed Python binding for open source usage (commercial licences are needed for some types of application) and partly because your author hasn’t used it before and wanted to learn about it. See the boxout (opposite) for a description of alternatives.
Qt comes with its own Qt Designer application and this can be used to create the GUI design using a dragand-drop tool. Once the GUI definition has been saved, it can be imported into a Python program and used, or the definition can be converted into native Python code. In this article, we are hand-coding the GUI and some explanation of how everything works follows.
Going loopy
Before we begin coding, let’s talk a little about some concepts. First of all, there is the event loop. When events occur in the GUI, entries are added to the event loop and these events can then be processed. For example, if you wanted to exit the program based on the Escape key being pressed, within the event loop you would need to look for the event that corresponds with the keypress and then write some code to exit the program. This leads us neatly into signals and slots. These are two sides of the same coin and provide a simple mechanism to link items together. For example, when a button in the GUI is pushed, it emits a signal. Using a method that is built into the QPushButton object, the signal emitted by the button being pushed can be linked to a slot. A slot can be thought of as the reference to a function, so when the button is pushed, it calls the linked-to function.