This article is sponsored by Yu Gang Said Writing Platform

Original author: AndroFarmer

Copyright notice: The copyright of this article belongs to the wechat public account Yu Gangshuo

What are Android Tings

Android Things (ATS) is an Internet of Things platform. It is based on Android and has been adapted to run on low-profile Internet of Things devices. It is also Android because it retains most of the features of the Android Framework. So with ats we can develop a series of intelligent hardware products without any knowledge of embedded (or, more accurately, some knowledge of it).

What can Android Tings do

To illustrate this problem, let’s say the opposite, what ats can’t do. Here’s an ats frame:


Hardware requirements for Android Tings development

Since Android Studio doesn’t offer an ATS emulator, we’ll need to have hardware that can handle the ATS system (like raspberry PI), as well as sensors, resistors, electronic buttons, bread boards, LED lights, and a whole host of other peripherals. Because iot (Internet of Things) development is often the operation of hardware, these peripherals can be better to experiment some demos. The following is the package of hardware I bought:

Raspberry PI stitching instructions

A lot of the development of ATS is to operate the hardware, so we need to study how to operate the peripheral devices, a very important method is to operate through the peripheral interface. See below:

What is the bus

The bus, the bus, is always getting you stuck


Raspberry pie support of bus types: GPIO, I2C, I2S, SPI, PWM, UART

I’m not a professional on buses either. To my understanding is to control different hardware equipment, and the electrical signal to do different processing standards. Here we are familiar with it first. The most commonly used is GPIO, which is the pin opened with the name BCM. Later we will control the device on the pin by the name. Detailed introduction about the bus and everyone can refer to this article: https://blog.csdn.net/haima1998/article/details/18729929

How to swipe ATS to raspberry PI development board

About this aspect of the introduction, there are still a lot of online, I searched the most is not lack of this kind of article, so here will not do a detailed introduction, a brief introduction of steps:

  1. Go to android Things Console and create a ROM of your own hardware. This is Google’s cloud management platform (where you can create roMs for hardware devices, publish OTA updates, etc.). https://partner.android.com/things/console/

  1. Here recommend a more convenient way: using official offer tools: android — things — the setup utility to download address: https://partner.android.com/things/console/#/tools after decompression as shown in figure:

    You can choose to operate according to your platform.

How to operate Android Things

Due to the particularity of the Internet of things, we do not have touch screen, buttons and other peripherals like Android to operate the device, so we need to connect the device in the following two ways.

1. Connect to the TTL device directly through USB

2. Connect the ATS to the router over a LAN (recommended). It is recommended to connect the ATS to the router through the monitor, mouse, and keyboard.

Common ADB commands

You can use these commands to better manage and use the ATS

  1. AndroidThings ADB Connect
  2. Disconnect AndroidThings adb Disconnect
  3. Adb shell uninstall After connecting to the ATS device with the ADB connect command, you can use Android Studio to develop, deploy, and debug the ats device as you would an app.

Demo and hardware construction – Light

This is an operation LED to its flashing demo, we use this demo to introduce the basic operation of the hardware method first look at the final result:

Hardware construction steps:

  1. A resistor and an LED lamp are connected to the positive pole of the breadboard in series through the breadboard
  2. The positive terminal of the breadboard is connected to a RASPberry PI GPIO bus port
  3. Another LED pin is connected to raspberry PI’s GROUND pin by jumper. Attached is my connection diagram:

For a more intuitive reference, see the official image below:

Ground is used to simulate the zero voltage line. The GPIO bus port can choose different voltages according to the added resistance and LED. I chose the 3.3V port named BCM2 here

Light code Analysis

public class LightActivity extends Activity {
    Handler mHandler;
    PeripheralManager mPeripheralManager;
    Gpio mLightGpio;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_light);
        mHandler = new Handler();
        mPeripheralManager = PeripheralManager.getInstance();
        try {
            mLightGpio = mPeripheralManager.openGpio("BCM2");
            mLightGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
            mHandler.post(mBlinkRunnable);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private Runnable mBlinkRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                if (mLightGpio == null)
                    return; mLightGpio.setValue(! mLightGpio.getValue()); mHandler.postDelayed(mBlinkRunnable, 1000); } catch (IOException e) { } } }; @Override protected voidonDestroy() {
        super.onDestroy();
        if(mLightGpio ! = null) { try { mLightGpio.close(); mLightGpio = null; } catch (IOException e) { e.printStackTrace(); }}}}Copy the code

Code is not much, all posted up, let’s analyze the code.

mPeripheralManager=PeripheralManager.getInstance();
mLightGpio= mPeripheralManager.openGpio("BCM2");
Copy the code

We call the openGpio method after passing the PeripheralManager singleton, passing in the name of the GPIO port, and then get an instance of the port control object GPIO, mLightGpio.

mLightGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_HIGH);
Copy the code

This code has two functions: 1. Set the level direction to the output direction; 2 Set the initial level to high and activate immediately. After this code is executed, the LED will turn on. We can do the same with the following three lines:

// Set the level direction to the output direction, set the initial level to low and immediately activate mlightgpio. setDirection(gpio.direction_out_initially_low); Mlightgpio.setactivetype (gpio.active_high) // Activate mlightgpio.setValue (gpio.active_high)true);
Copy the code

Use mlightgpio.setValue (! Mlightgpio.getvalue ()) to change the level activation state to achieve the LED flashing, so that the LED can blingbling.

Finally, there are two main differences between the ATS project and standard Android:

  1. Ats project permissions do not require dynamic user authorization, but are directly identified in the MANIFEST, such as access to GPIO bus ports and the permissions required for registered user drivers described below
<uses-permission android:name="com.google.android.things.permission.USE_PERIPHERAL_IO"/>
<uses-permission android:name="com.google.android.things.permission.MANAGE_INPUT_DRIVERS" />
Copy the code
  1. After the ATS project is deployed on the hardware, you can set it to stop, restart unexpectedly and start automatically. In this way, the highly available status of the devices in the Internet of Things can be guaranteed and the device cannot be used due to program crash. For details, add the following intent-filter to the entry Activity:
 <intent-filter>
     <action android:name="android.intent.action.MAIN"/>
     <category android:name="android.intent.category.HOME"/>
     <category android:name="android.intent.category.DEFAULT"/>
 </intent-filter>
Copy the code

User-driven -userdriver

So-called user-driven is ats allows you to convert the electrical signals of the corresponding hardware system events, such as a button click event registration into keyboard key events in the system, the temperature sensor system of registered electrical signals into the existing sensor events, so that each component can be very convenient use the standard framework apis to operate hardware.

Take a chestnut

This example shows how to register the button press event signal as the key event of the keyboard, so that the button becomes a keyboard that can be clicked and pressed. Once registered as a system event, it can be used in various components of the application. Demo effect:

Hardware installation diagram:

Take a look at the code:

package com.androfarmer.button;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.view.KeyEvent;

import com.google.android.things.pio.Gpio;
import com.google.android.things.pio.GpioCallback;
import com.google.android.things.pio.PeripheralManager;
import com.google.android.things.userdriver.UserDriverManager;
import com.google.android.things.userdriver.input.InputDriver;
import com.google.android.things.userdriver.input.InputDriverEvent;
import java.io.IOException;

public class KeyCodeDriverService extends Service {

    private InputDriver mDriver;
    private Gpio mButtonGpio;
    private static final int KEY_CODE = KeyEvent.KEYCODE_A;

    @Override
    public void onCreate() { super.onCreate(); MDriver = new inputDriver.builder ().setName()"Button2Keyboard") .setSupportedKeys(new int[]{KEY_CODE}) .build(); / / registration by UserDriverManager created above driver UserDriverManager manager = UserDriverManager. GetInstance (); manager.registerInputDriver(mDriver); PeripheralManager peripheralManager = PeripheralManager.getInstance(); try { mButtonGpio = peripheralManager.openGpio("BCM21"); // Set the level direction to input mbuttongpio.setdirection (gpio.direction_in); / / set the activation type mButtonGpio. SetActiveType (Gpio. ACTIVE_LOW); / / set to monitor events: level interrupt event change, Gpio. EDGE_BOTH / / means level from low to high interrupt and from high to low interrupt is triggered the callback mButtonGpio. SetEdgeTriggerType (Gpio. EDGE_BOTH); / / set the level changes of the listener mButtonGpio. RegisterGpioCallback (newGpioCallback() {
                @Override
                public boolean onGpioEdge(Gpio gpio) {
                    try {
                        Log.d("-------------button",gpio.getValue()+""); boolean pressed=gpio.getValue(); InputDriverEvent event = new InputDriverEvent(); event.setKeyPressed(KEY_CODE, pressed); mDriver.emit(event); } catch (IOException e) { e.printStackTrace(); } / / returntrueThe representative has been listening,falseOn behalf of listening oncereturn true; }}); } catch (IOException e) { e.printStackTrace(); } } @Override public voidonDestroy() { super.onDestroy(); . / / contact registered UserDriverManager manager = UserDriverManager getInstance (); manager.unregisterInputDriver(mDriver); // Close gPIO port try {mButtongpio.close (); mButtonGpio = null; } catch (IOException e) { e.printStackTrace(); } } @Override public IBinder onBind(Intent intent) {returnnull; }}Copy the code

The comments to the code are already very detailed and will not suffice to explain. Here are the steps

  1. Use InputDriver to create a basic driver information object
  2. Register the driver with UserDriverManager
  3. PeripheralManager processes electrical signals from specific peripheral hardware
  4. Emit the InputDriverEvent event through the EMIT method of InputDriver, so that each component of the system can respond to this event
  5. Don’t forget to unregister and close ports when no longer in use

User-driven type

It is mainly divided into four categories:

  1. Location Location driver
  2. Input User Input event driver
  3. Sensor Sensor driver
  4. LoWPAN

A further explanation of user-driven

For those of you who have done Android development, this is easy, but the concept of user driven is probably the first time we have heard of it. The ATS is modular in design. An ATS hardware board contains only basic hardware modules such as network modules, cpus, and memory modules. After we get the basic board of ats system, if we want to develop specific Internet of things products, we may need to connect peripheral sensors to realize specific functions, such as temperature sensors and smoke alarms.

Sensors in the market are complex, and if we mix business logic with the operation of hardware sensors, then obviously our code is fragile and not portable, and it won’t work with other sensors in the same class. So users drive the emergence of a very good solve the problem, no matter how many kinds of similar other models have peripheral hardware, we only need to write the corresponding user driven to register it into the framework has been implemented sensor events, so that the business logic just dealing with standard framework API, regardless the specific use which kinds of sensors.

Attach an open source project, which implements used widely in the market a lot of hardware user-driven https://github.com/androidthings/contrib-drivers interested students can go to study under the different types of users drive is how to write

Ps: in this paper, a lot of content and the case from the website, see https://developer.android.com/samples/?technology=iot&language=java for more cases

Welcome to pay attention to wechat public number, receive first-hand technical dry goods