Share
Embed
GDG DevFest Kansas city - Connect your Phone and Home with Firebase and Android Things
Slides of the presentation about Android Things and Firebase done at the GDG DevFest Kansas City
James Coggan
February 17, 2018
Transcript
186 slides
-
James Coggan Connect your Phone and Home with
Firebase and Android Things https://jamescoggan.com @mad_team -
Android vs Android Things ! Main app started automatically !
Android Things support Library ! Permissions are free (reboot required for dangerous ones) ! Google play services: ◦ Firebase ▪ Realtime database ▪ Cloud messaging ▪ Etc ◦ Google cloud platform ◦ Google cloud IoT ◦ ... -
Android vs Android Things ! AdMob ! Android Pay !
Full screen display (no status bar, notifications or navigation buttons) ! Sign-In ! System apps (Calendar, Telephony, Settings..) ! Display is optional -
Why Android Things? ! Kotlin :) ! OS and Framework
Maintained by Google ! OTA updates ! Android community ! Android libraries ! Reusable code/infrastructure -
Why Android Things? A bundle is a zip file that
contains the following: ! bootanimation.zip: Boot animation located in the root directory ! <user-space driver>.apk:User-space driver as a service (action=BOOT_COMPLETED) ! <main>.apk: (Required) The apk for the main entry point (action=MAIN, category=IOT_LAUNCHER) ! <sub>.apk:One of any number of apks that is launched by the main apk -
Update policy ! POLICY_CHECKS_ONLY - Only check for an available
update. ! POLICY_APPLY_ONLY - Download and apply an available update. ! POLICY_APPLY_AND_REBOOT - Download and apply an available update. Reboot the device automatically. This is the default policy. -
<!-— Things manifest file —-> … <application android:name=".ThingsApplication"> <uses-library android:name="com.google.android.things"
/> … </application> Getting started -
Getting started <!—- Things manifest file —-> <activity android:name=".MainActivity"> <intent-filter>
<!-- Launch activity as default from Android Studio --> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> -
Getting started <activity android:name=".MainActivity"> <intent-filter> <!-- Launch activity as default
from Android Studio --> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <!-- Launch activity automatically on boot --> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.IOT_LAUNCHER" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> -
Supported I/Os ! General Purpose Input/Output (GPIO): Binary ! Pulse
Width Modulation (PWM): Servo motors, DC motors ! Inter-Integrated Circuit(I2C) ! Serial Peripheral Interface (SPI) ! Universal Asynchronous Receiver Transmitter (UART) -
val gpioForLED: String // Pin 31 get() { return when
(Build.DEVICE) { DEVICE_RPI3 -> "BCM6" } } -
val gpioForLED: String // Pin 31 get() { return when
(Build.DEVICE) { DEVICE_RPI3 -> "BCM6" DEVICE_IMX6UL_PICO -> "GPIO4_IO22" DEVICE_IMX7D_PICO -> "GPIO2_IO02" } } -
val gpioForLED: String // Pin 31 get() { return when
(Build.DEVICE) { DEVICE_RPI3 -> "BCM6" DEVICE_IMX6UL_PICO -> "GPIO4_IO22" DEVICE_IMX7D_PICO -> "GPIO2_IO02" else -> throw IllegalStateException("Unknown Build.DEVICE " + Build.DEVICE) } } -
val gpioForButton: String // Pin 40 get() { return when
(Build.DEVICE) { DEVICE_RPI3 -> "BCM21" DEVICE_IMX6UL_PICO -> "GPIO2_IO03" DEVICE_IMX7D_PICO -> "GPIO6_IO14" else -> throw IllegalStateException("Unknown Build.DEVICE " + Build.DEVICE) } } -
buttonGpio = service.openGpio(gpioForButton) buttonGpio?.setDirection(Gpio.DIRECTION_IN) buttonGpio?.setEdgeTriggerType(Gpio.EDGE_BOTH) buttonGpio?.registerGpioCallback(object : GpioCallback() { override
fun onGpioEdge(gpio: Gpio?): Boolean { return true } } -
buttonGpio = service.openGpio(gpioForButton) buttonGpio?.setDirection(Gpio.DIRECTION_IN) buttonGpio?.setEdgeTriggerType(Gpio.EDGE_BOTH) buttonGpio?.registerGpioCallback(object : GpioCallback() { override
fun onGpioEdge(gpio: Gpio?): Boolean { setLed(gpio?.value ?: false) return true } } -
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); PeripheralManagerService service
= new PeripheralManagerService(); try { bus = service.openI2cDevice(I2C_ADDRESS, BMP280_TEMPERATURE_SENSOR_SLAVE); calibrationData[0] = bus.readRegWord(REGISTER_TEMPERATURE_CALIBRATION_1); calibrationData[1] = bus.readRegWord(REGISTER_TEMPERATURE_CALIBRATION_2); calibrationData[2] = bus.readRegWord(REGISTER_TEMPERATURE_CALIBRATION_3); …. private static int readSample(byte[] data) { // msb[7:0] lsb[7:0] xlsb[7:4] int msb = data[0] & 0xff; int lsb = data[1] & 0xff; int xlsb = data[2] & 0xf0; // Convert to 20bit integer return (msb << 16 | lsb << 8 | xlsb) >> 4; } } https://github.com/blundell/androidthings-i2c-input -
sensor = RainbowHat.openSensor() sensor?.setTemperatureOversampling(Bmx280.OVERSAMPLING_1X) sensor?.setPressureOversampling(Bmx280.OVERSAMPLING_1X) val temperature = sensor?.readTemperature() ?:
0f val pressure = sensor?.readPressure() ?: 0f val value = TemperatureAndPressure(temperature, pressure) saveTemperatureAndPressure(value) -
interface Sensor<out T> { fun start(onStateChangeListener: OnStateChangeListener<T>) fun stop() interface
OnStateChangeListener<in T> { fun onStateChanged(state: T) } } -
Setting up Firebase https://console.firebase.google.com • Create a new Firebase project
• Add a new Android app to the project with your package name • Enable anonymous login on (temporarily) -
Setting up Firebase https://console.firebase.google.com • Create a new Firebase project
• Add a new Android app to the project with your package name • Enable anonymous login on (temporarily) -
• Setup a database // Database { "home" :
{ "light" : false, "pressure" : 0, "temperature" : 0 } } -
data class HomeInformation( var light: Boolean = false, var pressure:
Float = 0f, var temperature: Float = 0f) -
// Base build.gradle for all modules buildscript { ... dependencies
{ classpath "com.google.gms:google-services:$playServices" } } -
// mobile & things build.gradle dependencies { ... implementation "com.google.firebase:firebase-core:$playServices"
implementation "com.google.firebase:firebase-database:$playServices" implementation "com.google.firebase:firebase-auth:$playServices" implementation "android.arch.lifecycle:extensions$archComponentsVersion" } apply plugin: "com.google.gms.google-services" -
// MainActivity.kt (Both modules - mobile and things) companion object
{ private val HOME = "home" } -
// MainActivity.kt (Both modules - mobile and things) companion object
{ private val HOME = "home" } override fun onCreate(savedInstanceState: Bundle?) { } -
// MainActivity.kt (Both modules - mobile and things) companion object
{ private val HOME = "home" } override fun onCreate(savedInstanceState: Bundle?) { val firebaseAuth = FirebaseAuth.getInstance() } -
// MainActivity.kt (Both modules - mobile and things) companion object
{ private val HOME = "home" } override fun onCreate(savedInstanceState: Bundle?) { val firebaseAuth = FirebaseAuth.getInstance() val reference = FirebaseDatabase .getInstance() .reference .child(HOME) } -
// Mobile Activity companion object { val LIGHT = "light"
} override fun onCreate(savedInstanceState: Bundle?) { ... } -
// Mobile Activity companion object { val LIGHT = "light"
} override fun onCreate(savedInstanceState: Bundle?) { ... lightToggle.setOnCheckedChangeListener({ _, state: Boolean -> }) } -
// Mobile Activity companion object { val LIGHT = "light"
} override fun onCreate(savedInstanceState: Bundle?) { ... lightToggle.setOnCheckedChangeListener({ _, state: Boolean -> databaseReference.child(LIGHT).setValue(state) }) } -
// Things Activity companion object { val PRESSURE = "pressure"
val TEMPERATURE = "temperature" } -
// Things Activity companion object { val PRESSURE = "pressure"
val TEMPERATURE = "temperature" } private val temperatureAndPressureListener = object : Sensor.OnStateChangeListener<TemperatureAndPressure> { } -
// Things Activity companion object { val PRESSURE = "pressure"
val TEMPERATURE = "temperature" } private val temperatureAndPressureListener = object : Sensor.OnStateChangeListener<TemperatureAndPressure> { override fun onStateChanged(state: TemperatureAndPressure) { } } -
// Things Activity companion object { val PRESSURE = "pressure"
val TEMPERATURE = "temperature" } private val temperatureAndPressureListener = object : Sensor.OnStateChangeListener<TemperatureAndPressure> { override fun onStateChanged(state: TemperatureAndPressure) { reference.child(TEMPERATURE).setValue(state.temperature) reference.child(PRESSURE).setValue(state.pressure) } } -
class HomeInformationLiveData (val dbReference : DatabaseReference) : LiveData<HomeInformation>() { private
val valueEventListener = object : ValueEventListener { } } -
class HomeInformationLiveData (val dbReference : DatabaseReference) : LiveData<HomeInformation>() { private
val valueEventListener = object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { } } } -
class HomeInformationLiveData (val dbReference : DatabaseReference) : LiveData<HomeInformation>() { private
val valueEventListener = object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { val newValue = snapshot.getValue(HomeInformation::class.java) value = newValue } } } -
class HomeInformationLiveData (val dbReference : DatabaseReference) : LiveData<HomeInformation>() { private
val valueEventListener = object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { val newValue = snapshot.getValue(HomeInformation::class.java) value = newValue } override fun onCancelled(error: DatabaseError) { Timber.w(error.toException(), "onCancelled") } } } -
class HomeInformationLiveData (val dbReference : DatabaseReference) : LiveData<HomeInformation>() { …
override fun onActive() { } override fun onInactive() { } } -
class HomeInformationLiveData (val dbReference : DatabaseReference) : LiveData<HomeInformation>() { …
override fun onActive() { dbReference.addValueEventListener(valueEventListener) } override fun onInactive() { } } -
class HomeInformationLiveData (val dbReference : DatabaseReference) : LiveData<HomeInformation>() { …
override fun onActive() { dbReference.addValueEventListener(valueEventListener) } override fun onInactive() { dbReference.removeEventListener(valueEventListener) } } -
// Things Activity private val lightsDataObserver = Observer<HomeInformation> { homeInformation
-> setLed(homeInformation?.light ?: false) } -
// Mobile Activity private val lightsDataObserver = Observer<HomeInformation> { homeInformation
-> pressureText.text =homeInformation?.pressure ?: 0f temperatureText.text = homeInformation?.temperature ?: 0f) } -
companion object { val HOME = "home" } private val
reference = FirebaseDatabase.getInstance().reference.child(HOME) -
companion object { val HOME = "home" } private val
reference = FirebaseDatabase.getInstance().reference.child(HOME) private val homeLiveData = HomeInformationLiveData(reference) -
// Mobile and Things Activity override fun onCreate(savedInstanceState: Bundle?) {
firebaseAuth.signInAnonymously() .addOnCompleteListener { } } -
// Mobile and Things Activity override fun onCreate(savedInstanceState: Bundle?) {
firebaseAuth.signInAnonymously() .addOnCompleteListener { task -> if (task.isSuccessful) { homeLiveData.observe(this, lightsDataObserver) } } } -
// Mobile and Things Activity override fun onStop() { super.onStop()
lightsLiveData.removeObserver { lightsDataObserver } } -
Nearby ! Pub/Sub ! Send messages, files or stream data
! No need for server ! Peer to peer ! Wifi or BLE -
// Android Things and Mobile val googleApiClient = GoogleApiClient.Builder(this) .addApi(Nearby.CONNECTIONS_API)
.addConnectionCallbacks() .build() -
// Android Things and Mobile val googleApiClient = GoogleApiClient.Builder(this) .addApi(Nearby.CONNECTIONS_API)
.addConnectionCallbacks(object : GoogleApiClient.ConnectionCallbacks { ) .build() -
// Android Things and Mobile val googleApiClient = GoogleApiClient.Builder(this) .addApi(Nearby.CONNECTIONS_API)
.addConnectionCallbacks(object : GoogleApiClient.ConnectionCallbacks { override fun onConnected(connectionHint: Bundle?) { } }) .build() -
// Android Things and Mobile val googleApiClient = GoogleApiClient.Builder(this) .addApi(Nearby.CONNECTIONS_API)
.addConnectionCallbacks(object : GoogleApiClient.ConnectionCallbacks { override fun onConnected(connectionHint: Bundle?) { startListening() } }) .build() -
// Android Things and Mobile val googleApiClient = GoogleApiClient.Builder(this) .addApi(Nearby.CONNECTIONS_API)
.addConnectionCallbacks(object : GoogleApiClient.ConnectionCallbacks { override fun onConnected(connectionHint: Bundle?) { startService() } override fun onConnectionSuspended(cause: Int) { Timber.e(“Failed”): } }) .build() -
// Mobile private fun startService() { Nearby.Connections.startDiscovery( googleApiClient, SERVICE_ID, endpointDiscoveryCallback,
DiscoveryOptions(Strategy.P2P_STAR)) } -
// Mobile private fun startService() { Nearby.Connections.startDiscovery( googleApiClient, SERVICE_ID, endpointDiscoveryCallback,
DiscoveryOptions(Strategy.P2P_STAR)) .setResultCallback { } } -
// Mobile private fun startService() { Nearby.Connections.startDiscovery( googleApiClient, SERVICE_ID, endpointDiscoveryCallback,
DiscoveryOptions(Strategy.P2P_STAR)) .setResultCallback { result -> when { result.status.isSuccess -> Timber.d("SUCCESS") else -> { Timber.w("FAILURE ${result.statusMessage}") } } } } -
private val endpointDiscoveryCallback = object : EndpointDiscoveryCallback() { override fun
onEndpointFound(endpointId: String?, info: DiscoveredEndpointInfo?) { } } -
private val endpointDiscoveryCallback = object : EndpointDiscoveryCallback() { override fun
onEndpointFound(endpointId: String?, info: DiscoveredEndpointInfo?) { endpointId?.let { } } } -
private val endpointDiscoveryCallback = object : EndpointDiscoveryCallback() { override fun
onEndpointFound(endpointId: String?, info: DiscoveredEndpointInfo?) { endpointId?.let { requestConnection(endpointId) } } } -
val requestConnectionCallback = object : ConnectionLifecycleCallback() { override fun onConnectionResult(endpointId:
String?, result: ConnectionResolution?) { } } -
val requestConnectionCallback = object : ConnectionLifecycleCallback() { override fun onConnectionResult(endpointId:
String?, result: ConnectionResolution?) { sendDataPayload(endpointId) } } -
private fun sendDataPayload(endpointId : String) { val credentials = getCredentials()
val adapter = moshi.adapter(Credentials::class.java) } -
private fun sendDataPayload(endpointId : String) { val credentials = getCredentials()
val adapter = moshi.adapter(Credentials::class.java) val dataToBeSent = adapter.toJson(credentials) } -
private fun sendDataPayload(endpointId : String) { val credentials = getCredentials()
val adapter = moshi.adapter(Credentials::class.java) val dataToBeSent = adapter.toJson(credentials) dataToBeSent?.let { } } -
private fun sendDataPayload(endpointId : String) { val credentials = getCredentials()
val adapter = moshi.adapter(Credentials::class.java) val dataToBeSent = adapter.toJson(credentials) dataToBeSent?.let { val bytes = dataToBeSent?.toByteArray() } } -
private fun sendDataPayload(endpointId : String) { val credentials = getCredentials()
val adapter = moshi.adapter(Credentials::class.java) val dataToBeSent = adapter.toJson(credentials) dataToBeSent?.let { val bytes = dataToBeSent?.toByteArray() Nearby.Connections.sendPayload(googleApiClient, endpointId, Payload.fromBytes(bytes)) } } -
// Android Things private fun startListening() { Nearby.Connections.startAdvertising( googleApiClient, appName,
SERVICE_ID, connectionLifecycleCallback, -
// Android Things private fun startListening() { Nearby.Connections.startAdvertising( googleApiClient, appName,
SERVICE_ID, connectionLifecycleCallback, AdvertisingOptions(Strategy.P2P_STAR)) -
// Android Things private fun startListening() { Nearby.Connections.startAdvertising( googleApiClient, appName,
SERVICE_ID, connectionLifecycleCallback, AdvertisingOptions(Strategy.P2P_STAR)) .setResultCallback {}) } -
// Android Things private fun startListening() { Nearby.Connections.startAdvertising( googleApiClient, appName,
SERVICE_ID, connectionLifecycleCallback, AdvertisingOptions(Strategy.P2P_STAR)) .setResultCallback { result -> when { result.status.isSuccess -> Timber.d("SUCCESS") else -> Timber.w("STATE_READY") }) } -
// Android Things private val connectionLifecycleCallback = object : ConnectionLifecycleCallback()
{ override fun onConnectionResult(endpointId: String?, result: ConnectionResolution?) { Timber.d("connectionResult from " + endpointId, result) } } -
// Android Things private val connectionLifecycleCallback = object : ConnectionLifecycleCallback()
{ override fun onConnectionResult(endpointId: String?, result: ConnectionResolution?) { Timber.d("connectionResult from " + endpointId, result) } override fun onDisconnected(endpointId: String?) { Timber.w("onDisconnected from " + endpointId) } } -
// Android Things private val connectionLifecycleCallback = object : ConnectionLifecycleCallback()
{ … override fun onConnectionInitiated(endpointId: String?, connectionInfo: ConnectionInfo?) { } } -
// Android Things private val connectionLifecycleCallback = object : ConnectionLifecycleCallback()
{ … override fun onConnectionInitiated(endpointId: String?, connectionInfo: ConnectionInfo?) { Timber.d("onConnectionInitiated from " + endpointId, connectionInfo) Nearby.Connections.acceptConnection( googleApiClient, endpointId, payloadCallback ) } } -
// Android Things private val payloadCallback = object : PayloadCallback()
{ override fun onPayloadReceived(endpointId: String?, payload: Payload?) { } } -
// Android Things private val payloadCallback = object : PayloadCallback()
{ override fun onPayloadReceived(endpointId: String?, payload: Payload?) { payload?.let { onDataReceived(payload.asBytes()) } } } -
private fun onDataReceived(data: ByteArray) { val jsonString = String(data) val
adapter = moshi.adapter(Credentials::class.java) } -
private fun onDataReceived(data: ByteArray) { val jsonString = String(data) val
adapter = moshi.adapter(Credentials::class.java) val credentials = adapter.fromJson(jsonString) } -
private fun onDataReceived(data: ByteArray) { val jsonString = String(data) val
adapter = moshi.adapter(Credentials::class.java) val credentials = adapter.fromJson(jsonString) credentials?.let { saveCredentials(credentials) } } -
https://github.com/jamescoggan/thingspresentationn • Common code in shared module • Nearby •
RainbowHat: ◦ Sensors ◦ Led ◦ Button • Philips Hue (in progress)