Android recently launchs the preview version of Android Things when IoT is popular.

[gallery size="full" columns="1" ids="3225"]

Android Things is basically the same as mobile app, and it's much more convenient for the Things Support Library to be used by developers.

In the first time, test whether Android Things can connect to NAS and quickly render NAS IoT applications through Node-Red + Dashboard.

Currently, the preview version of Android Things only supports 3 IoT development devices:

  • Intel Edison

  • NXP Pico i.MX6UL (Taiwan seems not easy to o buy this development board)

  • Raspberry Pi 3


Other development devices should add more options in the future.

Here's how to use the combination of Android Things + NAS.

Tools have to be prepared:

Hardware:

  1. Raspberry Pi 3 + SD Card

  2. led

  3. resistance

  4. switch

  5. Breadboard + jumper

  6. NAS


Software:

  1. Android Studio (requires 2.2 or above)

  2. Android adb debug tool

  3. Button and LED sample for Android Things


Aftering preparing tools, you can refer to this link and install Android Things on the Raspberry Pi 3.

Regarding Android Things image, this part is the same as the image setting provided by Raspberry Pi, except that the operating system running on it is different.

Once completed, power up the Raspberry Pi 3 and test it later with the adb tool.

Connect to Android Things via the following command, and you will see the connected to xxx message when you successfully connect.

$ adb connect "ip-address"

Connected to xxxxx:5555

After successfully connecting, the next step is to write the code for Android Things.

Download the sample just first and compile it with Android Studio.

If you have just successfully connected via adb connect, you can push it directly to Android Things via Android Studio.

[gallery columns="1" size="full" ids="3226"]

After successful push, you can see the message that the program started successfully in the debug message bar.

12-30 10:01:48.665 20111-20111/com.example.androidthings.button I/ButtonActivity: Starting ButtonActivity

12-30 10:01:48.683 20111-20111/com.example.androidthings.button I/ButtonActivity: Configuring GPIO pins

12-30 10:01:48.690 20111-20111/com.example.androidthings.button I/ButtonActivity: Registering button driver

Next, we need to connect the newly prepared LED, resistor and Button, please refer to the figure below.

[gallery size="full" columns="1" ids="3227"]

After the completion, open Android Things, and then execute the program, you can directly control the LED switch through the button, press the button LED light will be constant, release it and go out. (Temporarily unable to find the button switch, with touch sensor instead)

[gallery size="full" columns="1" ids="3228"]

Now we can  first explain what is added in Things Support Library!

As you can see from gradle config, there are two more libraries.

The first line, mainly used to handle the processing of button events, is mainly for the processing of buttons using GPIO.

The second line is the Things Support Library, mainly Android Things related dependency library.

Compile 'com.google.android.things.contrib:driver-button:0.1'

Provided 'com.google.android.things:androidthings:0.1-devpreview'

Note: Currently Android Things is provided to handle hardware-related drivers. You can find out which types of support are currently available from GitHub in Android Things (currently supports 12).

Here's the button to use the Things Support Library to control the connection to GPIO.
PeripheralManagerService pioService = new PeripheralManagerService();

Try {

   Log.i(TAG, "Configuring GPIO pins");

   mLedGpio = pioService.openGpio(BoardDefaults.getGPIOForLED());

   mLedGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);



   Log.i(TAG, "Registering button driver");

   // Initialize and register the InputDriver that will emit SPACE key events

   // on GPIO state changes.

   mButtonInputDriver = new ButtonInputDriver(

           BoardDefaults.getGPIOForButton(),

           Button.LogicState.PRESSED_WHEN_HIGH,

           KeyEvent.KEYCODE_SPACE);

   mButtonInputDriver.register();

} catch (IOException e) {

   Log.e(TAG, "Error configuring GPIO pins", e);

}




 

1: PeripheralManagerService is used to manage hardware services on the development board

4: Set the LED GPIO pin, currently use the BoardDefaults to get the pin of BCM6 (refer to related pin out)

5: Set pin out to low potential

10: Use the driver-button library to control the state of the button, use BCM21 as input, and preset when the button is pressed high (PRESSED_WHEN_HIGH)

14: Register the button, and use the KeyEvent method to handle the press event.

After the button is successfully registered, the button's events can be handled via onKeyDown and onKeyUp callback.
@Override

Public boolean onKeyDown(int keyCode, KeyEvent event) {

   If (keyCode == KeyEvent.KEYCODE_SPACE) {

       // Turn on the LED

       setLedValue(true);



       Return true;

   }



   Return super.onKeyDown(keyCode, event);

}



@Override

Public boolean onKeyUp(int keyCode, KeyEvent event) {

   If (keyCode == KeyEvent.KEYCODE_SPACE) {

       // Turn off the LED

       setLedValue(false);



       Return true;

   }



   Return super.onKeyUp(keyCode, event);

}



/**

* Update the value of the LED output.

*/

Private void setLedValue(final boolean value) {

   Try {

       mLedGpio.setValue(value);

   } catch (IOException e) {

       Log.e(TAG, "Error updating GPIO value", e);

   }

}

2, 14: callback when the button is pressed or released.

30: Mainly used to process the LED to be high or low when the button is pressed.

The above is how to control the LED's on and off through the button. How do we transfer the status of the LED back to the NAS and return the LED status? In fact, it is very simple, we can implement MQTT on Android Things and return the LED status.

First, first add the MQTT library to gradle config.

Compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.0.2'

Compile 'org.eclipse.paho:org.eclipse.paho.android.service:1.0.2'

Here's how to implement MQTT publish and subscribe and pass the data back to MQTT Server
Public class PiActivity extends Activity implements MqttCallback{



...

...



Public void connectMQTT(){

   Try {

       MemoryPersistence persistence = new MemoryPersistence();

       Client = new MqttClient("tcp://your-mqtt-server:1883", "JarvisPi", persistence);

       Client.connect();

       client.setCallback(this);

       Client.subscribe("PiLEDStatus");

   } catch (MqttException e) {

       e.printStackTrace();

   }

}



@Override

Public void connectionLost(Throwable cause) {

   Log.d(TAG, "MQTT Connection Lost!");

}



@Override

Public void messageArrived(String topic, MqttMessage message) throws Exception {

   Log.d(TAG, "LED Status:" + topic + " msg:" + message.getPayload().toString());

}



@Override

Public void deliveryComplete(IMqttDeliveryToken token) {}



}





1, 19, 24, 29: Implementation MqttCallback

8: The data is temporarily stored in memory. If you do not use this method, there will be an error message.

9: Connection information, including MQTT server location, clientId

11: Applying MqttCallback

12: subscribe PiLEDStatus

19: Connection failed callback

24: Received a message from PiLEDStatus



Modify the just setLedValue and add the push of the MQTT message.



/**

* Update the value of the LED output.

*/

Private void setLedValue(final boolean value) {

   Try {

       mLedGpio.setValue(value);



       MqttMessage message = new MqttMessage();

       If(value) {

           message.setPayload("true".getBytes());

       }else{

           message.setPayload("false".getBytes());

       }

       Try {

           Client.publish("PiLEDStatus", message);

       } catch (MqttException e) {

           e.printStackTrace();

       }

       Log.i(TAG, "PiLEDStatus send...");

       

   } catch (IOException e) {

       Log.e(TAG, "Error updating GPIO value", e);

   }

}

 

8 – 13: Create an MQTT message container

15: publish PiLEDStatus and send the message to MQTT Server

 

After completing the implementation of MQTT, compile the program again and push it to Android Things.

 

Next, open the Node-Red of the NAS, create an MQTT Node, and subscribe PiLEDStatus to point the output to the Node-Red Dashboard.

[gallery columns="1" size="full" ids="3229"]

 

After the deployment of Node-Red, you can instantly observe the status of each button pressed.

[gallery columns="1" size="full" ids="3230"]

Android Things is still a preview version, but the integrity of the current support library is quite high, and the size of the image is also compressed at 200MB. It seems to be a lightweight Android Things. I hope that after the official version is released, support will be provided. The function can be more.

 

 

 
arrow
arrow
    全站熱搜

    tttt 發表在 痞客邦 留言(0) 人氣()