How To Create A Home Appliance App For Embedded And Android

About the project

Building house automatization with the Home Appliance application and interact with Android devices using Firebase platform in order to store the data. You will also learn how to use external Python scripts on the Java application, GPIO interfacing, and building a graphical user interface using TotalCross.

Project info

Difficulty: Easy

Platforms: AndroidRaspberry PiPythonJavaArm

Estimated time: 1 hour

License: MIT license (MIT)

Items used in this project

Hardware components

LED - RGB Clear Common Cathode LED - RGB Clear Common Cathode Common LED (any type) x 1
DHT11 Basic Temp Humidity Sensor DHT11 Basic Temp Humidity Sensor DHT11 temperature and humidity sensor x 1
Raspberry Pi 3 Model B Raspberry Pi 3 Model B Raspberry Pi (any type) x 1
Resistor Network - 330 Ohm (6-pin bussed) Resistor Network - 330 Ohm (6-pin bussed) Resistor for limit thee led current (recommends 330R to 1K ) x 1
Display RK043FN02H-CT Display RK043FN02H-CT Display RK043FN02H-CT to interact with GUI x 1
Half-size Breadboard Half-size Breadboard Breadboard for mounting x 1

Software apps and online services

VSCode VSCode https://code.visualstudio.com/
TotalCross plugin for VScode TotalCross plugin for VScode https://marketplace.visualstudio.com/items?itemName=totalcross.vscode-totalcross
Java 11+ Java 11+ https://www.oracle.com/br/java/technologies/javase-jdk11-downloads.html
Git Git https://github.com/

Story

Building home automation with Java for Linux Arm and mobile devices

In this article, you will learn how to automate your house with the Home Appliance application and how to interact with your Android device using some great technologies, including the Firebase platform in order to store the data. You will also learn how to use external Python scripts on the Java application, GPIO interfacing, and how to build a graphical user interface using TotalCross.

Introduction:

First of all, let's talk about the running application. The image below shows the running application on Raspberry Pi  4 with a small 5-inch display.

Picture 1 - Embedded application

The embedded application is based on reading the commands list from the Firebase service, and running them on Raspberry Pi. This method allows communication between the embedded and the mobile application.

The mobile application is a little simpler, without the sensor readings, it has a simple UI which is used only to change the temperature, with two buttons for power. The mobile app’s job is to send commands to the Firebase server which will be executed by the embedded application.

Picture 2 - Mobile application

To build the application you need to install the following tools:

For the physical test you will need the following additional hardware:

Source code

Clone the source code from https://github.com/TotalCross/embedded-samples/tree/main/home-appliance and open the project.

After opening the project on VScode, make a first run of the application to generate runtime files. To do so, right click on the HomeApplianceXMLApplication.java file and then click on RUN. After the first run, just close the application, and now we can go to the configuration.

Configuring the home appliance application

In this project, we have two main configuration files: the FirebaseConfig.java and the UIconfig.java. The first one we use to configure the Firebase service and the second one we use to select the UI of the project.

UIconfig.java

On the UI configuration, we can select between two interfaces, the LIGHT_XML_LAYOUT, for use on embedded devices with restricted resources, and the  BEAUTIFUL_XML_LAYOUT. We can change the selected interface by changing the variable LAYOUT_TO_INITIALIZE.

  1. public abstract class UIConfig {
  2. private UIConfig() {
  3. }
  4. /**
  5. * Lightweight layout to low RAM devices
  6. */
  7. public static final String LIGHT_XML_LAYOUT =
  8. "xml/homeApplianceLightXML.xml";
  9. /**
  10. * Beautiful layout for more advanced devices
  11. */
  12. public static final String BEAUTIFUL_XML_LAYOUT=
  13. "xml/homeApplianceBeautifulXML.xml";
  14. /**
  15. * App XML layout that will be loaded by MainWindow
  16. */
  17. public static final String LAYOUT_TO_INITIALIZE = BEAUTIFUL_XML_LAYOUT;
  18. }

In the following, you can see the two possible GUIs:

Picture 3 - The lighter interface

Picture 4 - The beautiful interface

FirebaseConfig.java

Using the Firebase configuration file, we're going to change the parameters for your Firebase application.

Change "YOUR AUTH KEY" to the authorization key given by Firebase, and change the "YOUR FIREBASE URL" to the URL of your firebase application

  1. public abstract class FirebaseConfig {
  2. private FirebaseConfig() {
  3. }
  4. /**
  5. * Firebase Realtime Database Secret Key.
  6. */
  7. private static final String FIREBASE_AUTH_KEY = "YOUR AUTH KEY";
  8. /**
  9. * Firebase Realtime Database Commands document base URL.
  10. */
  11. public static final String COMMANDS_FIREBASE_URL = "YOUR FIREBASE URL"
  12. + FIREBASE_AUTH_KEY;
  13. }

Working on the application

Now with the UI and Firebase configured, the application is ready to be deployed and run in the embedded device, but first we're going to talk a little bit about working on the application and its interaction with the environment.

UI from XML

To make it easiest to create the interface we are using the Knowcode-Xml XmlContainerLayout. This feature allows us to use a pre-mounted interface with its XML; in this case, we are using the chosen XML on the UI configuration file.

  1. final XmlContainerLayout xmlCont = (XmlContainerLayout) XmlContainerFactory
  2. .create(UIConfig.LAYOUT_TO_INITIALIZE);
  3. // Swapping from MainWindow to XmlContainerLayout.
  4. swap(xmlCont);

Event mapping

For the user to interact with the application, we need to add events to itself. To do this, we’ll instance the object reference on Java using the Knowcode-XML, for example, the minus button

  1. // Getting Button instance that matches with "android:id" tag in xml.
  2. // This button will decrease temp inside selector
  3. final Button minusButton=(Button) xmlCont.getControlByID("@+id/minus");

After instantiating the object, you can make any changes to it. For example, we add the press listener to the minus button.

  1. minusButton.addPressListener(new PressListener() {
  2. @Override
  3. public void controlPressed(ControlEvent e) {
  4. if (insideTempLabel != null) {
  5. // Sets label text decreasing temp
  6. insideTempLabel.setText(Convert.toString(--insideTemp));
  7. }
  8. }
  9. });

Firebase communication

The Firebase communication is implemented on the listening function, which is responsible for making HTTP requests to the real-time database, with the credentials settings that we configured on the previous topic. The HTTP response from the database should contain the commands sent by the mobile application; the embedded one gets the list of commands and does the necessary actions to accomplish them.

  1. URI uri = new URI(FirebaseConfig.COMMANDS_FIREBASE_URL.concat("&orderBy="timestamp""));
  2. // Performing query
  3. String response = HTTPConnection.doGet(uri);
  4. if (response == null || response.equalsIgnoreCase("null"))
  5. return; // returning to prevent NullPointerException
  6. /*
  7. * Parsing response in JSON Objects to get commands from remote.
  8. */
  9. JSONObject data = new JSONObject(response);
  10. List<JSONObject> listCommands = new ArrayList<JSONObject>();
  11. JSONArray ids = data.names();
  12. JSONArray array = data.toJSONArray(ids);
  13. for (int i = 0; i < array.length(); i++) {
  14. JSONObject command = array.getJSONObject(i);
  15. String id = ids.getString(i);
  16. command.put("id", id);
  17. listCommands.add(command);
  18. }

GPIO usage

The LED control is made by using the “gpiod” feature from the TotalCross framework. This feature interacts with the GPIO kernel device driver, allowing the application to control the GPIO chip.

  1. import totalcross.io.device.gpiod.GpiodChip;
  2. import totalcross.io.device.gpiod.GpiodLine;

  1. if (Settings.platform.equalsIgnoreCase("linux_arm")) {
  2. // Opening Gpio chip
  3. gpioChip = GpiodChip.open(0);
  4. // Gets Gpio line
  5. pin = gpioChip.line(21);
  6. // Request line as output and set the initial state to low
  7. pin.requestOutput("CONSUMER", 0);
  8. }

Temperature and humidity reading

To read the temperature of the environment, we’ll use the DHT11 sensor, which is capable of reading the temperature and humidity data and sending it through the one wire protocol to the embedded device.

In the application, this communication is implemented by a Python script which uses the Adafruit_DHT library to read data from the sensor. On Java we instance the Python script on a Linux process and read its outputs, returning the reading of the Python process to the main application.

  1. public String readTemp() {
  2. // Returns default 18 value if it's not running in a embedded device.
  3. if (!Settings.platform.equalsIgnoreCase("linux_arm"))
  4. return "18";
  5. // Input from program
  6. String readValue = "error";
  7. try {
  8. Vm.debug("starting read sensor");
  9. // Process initialization.
  10. final Process process = Runtime.getRuntime().exec("python3 dht.py");
  11. // Writes output into process.
  12. process.getOutputStream().write("".getBytes(), 0, "".getBytes().length);
  13. // Waits for dht response.
  14. process.waitFor();
  15. // Getts the lineReader for the process.
  16. final LineReader lineReader = new LineReader(Stream.asStream(process.getInputStream()));
  17. // Reads the response.
  18. readValue = lineReader.readLine();
  19. Vm.debug(readValue);
  20. Vm.debug("finishing read sensor");
  21. } catch (java.io.IOException e) {
  22. e.printStackTrace();
  23. readValue = "40";
  24. } catch (InterruptedException e) {
  25. e.printStackTrace();
  26. } catch (Exception e) {
  27. e.printStackTrace();
  28. }
  29. // Returns the validated temp.
  30. return validateTemp(readValue);
  31. }

Building and Deploying

After editing the source code, it's time to build the application; in pom.xml it's possible to see and change the target systems, and make sure that the targets “Linux Arm” and “Android” are available.

If you are using the VScode press F1 on the keyboard, select “TotalCross: Package” and wait for the package to finish. When the package is done, you can see the installation files in the “target” folder.  

If you want to deploy the app through the SSH you can select the option “TotalCross: Deploy and Run” and then provide information about the SSH connection (User,IP,Password,Path).

Conclusion

Now with everything built and deployed it is time for testing. Run the application on Android and the embedded system and start testing the Firebase communication and DHT11 data readings on the Home appliance application.

Feel free to edit, explore and use the TotalCross framework to tune up your embedded applications.

Code

Home appliance application

Source code and instructions about home appliance application

Credits

Photo of TotalCross

TotalCross

TotalCross is an open source cross-platform framework developed to bring speed to GUI (Graphical User Interface) creation for embedded devices. TotalCross has the development benefits from Java without the need of Java running on the device, as it uses its own bytecode and virtual machine (TC bytecode and TCVM), created specifically for performance enhancement. TotalCross runtime is currently at 5MB to bring mobile grade user experience even for low-end MPUs.

   

Leave your feedback...