DZone
IoT Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > IoT Zone > Synchronizing Android Things With Firebase

Synchronizing Android Things With Firebase

Learn how to synchronize Android Things with Firebase, enabling you to create real-time IoT apps by linking your Firebase database to your board.

Francesco Azzola user avatar by
Francesco Azzola
CORE ·
Oct. 12, 17 · IoT Zone · Tutorial
Like (2)
Save
Tweet
6.03K Views

Join the DZone community and get the full member experience.

Join For Free

This article describes how to synchronize Android Things with Firebase so that we can control an RGB LED remotely in real time. In more detail, this project shows how to control a remote RGB LED in real time over the air, changing some value in the Firebase database. As you may already know Android Things is a branch of the Android OS. Therefore, Android Things supports Firebase out of the box.

This tutorial describes all the step necessary to integrate Android Things with Firebase and how to connect the RGB LED to the Android Things board. Synchronizing Android Things with Firebase, this IoT project changes, in real time, the LED color according to the value we set using Firebase.

In this tutorial, we assume you are already familiar with the Android Things OS and you have already installed it. If this is the first time you have used Android Things, you can read how to install the Android Things OS on your board.

This Android Things IoT project can be further extended so that we can synchronize Android Things with Firebase using different types of information. There are several scenarios where the synchronization between Android Things and Firebase plays an important role so it is important to know how to do it.

Before diving into this Android Things Firebase synchronization project, it is useful to clarify which components we will use:

  • Raspberry Pi 3 (or an Android Things compatible board).
  • A common anode RGB LED.

Moreover, you need a Firebase account so that you can test this Android Things IoT project.

How to Synchronize Android Things With Firebase Projects

Now we know the components we will use in this project, it is useful to have an overview of the synchronization. The picture below describes how the project works:

Once we have connected Android Things to Firebase, whenever we change a value in the Firebase database, the new value triggers an event so that the synchronization between Android Things and Firebase database takes place, transferring the new value to the Android Things board that, in turn, sets the RGB LED color.

How to Setup Firebase With Android Things

In this section, we will describe how to configure a Firebase project so that we can integrate it with Android Things. The first step is creating a free account. Once you have your free account, you can create a new Firebase project as shown below:

The next step is configuring your app:

During this configuration process, you have to follow the Firebase instructions. Finally, before interacting with Firebase, it is necessary to modify the security aspects:

Finally, we can configure our database that will hold the LED colors:

At the app level, the build.gradle looks like:

......
dependencies {
    provided 'com.google.android.things:androidthings:0.4.1-devpreview'
    compile 'com.google.firebase:firebase-core:11.4.0'
    compile 'com.google.firebase:firebase-database:11.4.0'
    apply plugin: 'com.google.gms.google-services'
}


How to Use Android Things With Firebase

Once you have followed the instructions during the Firebase project setup, you are ready to start coding the Android Things app. All the Firebase dependencies and configuration are now ready. We can dive into the Android Things project. As described previously, the Android Things app has to listen to the Firebase value changes and react, controlling the RGB LED.

The RGB LED has three pins — one for each color — and we connect them to the Raspberry GPIO pins. According to the value in the Firebase database, the Android Things app turns on or off each GPIO pin controlling the LED color. This app does not have a UI because Android Things is controlled remotely.

In order to create this Android IoT app, it is necessary to create a new Android Things project cloning the template project. If you are new and this is the first time you have approached Android Things, you can follow this tutorial describing how to get started with Android Things.

In the previous step, we created a table in the Firebase database containing three different fields representing the LED colors. In order to hold the new Firebase values, we have to create a simple POJO class that represents the table:

public class RGBColor {

    private int red;
    private int green;
    private int blue;

    public RGBColor() {}

    public int getRed() {
        return red;
    }

    public void setRed(int red) {
        this.red = red;
    }

    public int getGreen() {
        return green;
    }

    public void setGreen(int green) {
        this.green = green;
    }

    public int getBlue() {
        return blue;
    }

    public void setBlue(int blue) {
        this.blue = blue;
    }
}


We will use this simple class to control the GPIO pins.

Now, we can focus our attention on the main activity that will handle all the synchronization between Android Things and Firebase. To this purpose, you can use the template Activity already configured in the project. In onCreate(), we have to initialize the connection with Firebase and get the reference to the PeripheralManagerService:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "onCreate");
    databaseRef = FirebaseDatabase.getInstance().getReference();
    databaseRef.addValueEventListener(veListener);
    pms = new PeripheralManagerService();
    initPin();
}


There, databaseRef is an instance of DatabaseReference. Moreover, the app adds a listener to the databaseRef to receive notifications when values change. Moreover, in this method, we initialize the pins that the app uses to control the LED:

private void initPin() {
    try {
        redPin = pms.openGpio("BCM26");
        redPin.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
        greenPin = pms.openGpio("BCM6");
        greenPin.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
        bluePin = pms.openGpio("BCM5");
        bluePin.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
    } catch (IOException ioe) {
        Log.e(TAG, "Unable to open pins");
    }
}


It is important to note that in the code above, the Android Things IoT app references the pin names directly. This is not a best practice if you want your app
to be portable on different boards. Anyway, for this tutorial, we can use the direct pin access.

Synchronizing Android Things With Firebase

Once the "hardware" part is ready and the pins are initialized, it is necessary to receive notifications when Firebase values change. To this purpose, it is necessary to define a listener:

private ValueEventListener veListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        RGBColor color = dataSnapshot.getValue(RGBColor.class);

        // update pins
        updatePin(redPin, color.getRed());
        updatePin(greenPin, color.getGreen());
        updatePin(bluePin, color.getBlue());
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};


The code above is really simple. The onDataChange method is invoked when one or more values in the database are changed. The class RGBColor, described previously, holds the new values. The last step is updating the pin, setting the right color:

private void updatePin(Gpio pin, int value) {
    try {
        pin.setValue(value > 0 ? false : true);
    } catch (IOException e) {
        e.printStackTrace();
    }
}


In this example, we suppose that if the value is more than zero, then the pin is on. Otherwise, it is off. Notice that we are using a common cathode LED. For this reason, we turn off the pin.

Now you can play using the Firebase console changing the RGB values to see how the LED changes colors.

Summary

At the end of this article, you have learned how to synchronize Android Things with Firebase so that we can control an Android Things board remotely in real time.

Android Things Android (robot) Firebase

Published at DZone with permission of Francesco Azzola, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Flutter vs React Native. How to Cover All Mobile Platforms in 2022 With No Hassle
  • How to Handle Early Startup Technical Debt (Or Just Avoid it Entirely)
  • Making Machine Learning More Accessible for Application Developers
  • How Does the Database Understand and Execute Your Query?

Comments

IoT Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo