SlideShare a Scribd company logo
James Coggan, MyDrive Solutions
Connect your Phone and Home
with
Firebase and Android Things
We are hiring!
https://www.mydrivesolutions.com/jobs
Q&A
sli.do
#thingstelaviv
A little bit about me..
James Coggan
Android tech lead
https://jamescoggan.com
@mad_team
What is Android Things?
Android + Internet of ThingsAndroid Things
The hardware
NXP Pico i.MX7D
Raspberry Pi 3 NXP Argon i.MX6UL
NXP Pico i.MX6UL
Development kits
NXP Pico i.MX7D Raspberry pi kit
Android
Android Things
What Android Things does support
What Android Things doesn’t support
Good to know
● Main application started on boot
● Permissions are free and set on reboot
● adb connect 192.168.1.111:5555
Why Android Things?
● Kotlin :)
● Maintained by Google
● OTA updates
● Android community
● Hardware agnostic
● Relatively cheap hardware
● Reusable code
Getting started
https://partner.android.com/things/console/u/0/#/tools
Getting started
Getting started
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)
Raspberry Pi NXP MX7D
val pioService = PeripheralManagerService()
try {
val pinName = "BCM6"
ledGpio = pioService.openGpio(pinName)
ledGpio?.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW)
} catch (e: IOException) {
e.printStackTrace()
}
val pioService = PeripheralManagerService()
try {
val pinName = "BCM21"
button = ButtonInputDriver(
pinName,
Button.LogicState.PRESSED_WHEN_LOW,
KeyEvent.KEYCODE_SPACE)
button?.register()
} catch (e: IOException) {
e.printStackTrace()
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
if (keyCode == KeyEvent.KEYCODE_SPACE) {
setLedValue(true)
return true
}
return super.onKeyDown(keyCode, event)
}
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
if (keyCode == KeyEvent.KEYCODE_SPACE) {
setLedValue(false)
return true
}
return super.onKeyUp(keyCode, event)
}
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)
}
}
val pinName = gpioForLED
ledGpio = pioService.openGpio(pinName)
...
val pinName = gpioForButton
button = ButtonInputDriver(
pinName,
Button.LogicState.PRESSED_WHEN_LOW,
KeyEvent.KEYCODE_SPACE)
...
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: ie: com.jamescoggan.thingspresentation
● Enable anonymous login on (temporarily)
● Setup a database
// Database
{
"light" : true
}
● Add the rules
// Rules - don’t expose your data for the world
{
"rules": {
".write": "auth != null",
".read": "auth != null",
}
}
// Base build.gradle for all modules
buildscript {
...
dependencies {
classpath "com.google.gms:google-services:$googleServicesClassVersion"
}
}
// mobile & things build.gradle
dependencies {
...
implementation "com.google.firebase:firebase-core:$playServicesVersion"
implementation "com.google.firebase:firebase-database:$playServicesVersion"
implementation "com.google.firebase:firebase-auth:$playServicesVersion"
implementation "android.arch.lifecycle:extensions:$androidArchComponentsVersion"
}
apply plugin: "com.google.gms.google-services"
// MainActivity.kt (Both modules - mobile and things)
override fun onCreate(savedInstanceState: Bundle?) {
FirebaseApp.initializeApp(this) // Move me to the Application class
val firebaseAuth = FirebaseAuth.getInstance()
val databaseReference = FirebaseDatabase.getInstance().reference
}
// MainActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
...
val databaseReference = FirebaseDatabase.getInstance().reference
firebaseAuth.signInAnonymously()
.addOnCompleteListener { task ->
if (task.isSuccessful) {
observeLightsData()
} else {
Timber.e(task.exception, "FirebaseAuth:failed")
}
}
}
// Light.kt
class FirebaseTables {
companion object {
val LIGHTS_BASE = "light"
}
}
data class Light(val light : Boolean)
class LightLiveData(val firebase: DatabaseReference) : LiveData<Light>() {
private val valueEventListener = object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val newValue = snapshot.getValue(Boolean::class.java) ?: false
value = Light(newValue)
}
override fun onCancelled(error: DatabaseError) {
}
}
override fun onActive() {
firebase.child(LIGHTS_BASE).addValueEventListener(valueEventListener)
}
override fun onInactive() {
firebase.child(LIGHTS_BASE).removeEventListener(valueEventListener)
}
}
// Things Activity
private val lightsDataObserver = Observer<Light> { lightState ->
Timber.d("LightState changed: ${lightState?.isOn}")
led.setValue(lightState?.isOn ?: false)
}
override fun onCreate(savedInstanceState: Bundle?) {
...
firebaseAuth.signInAnonymously()
.addOnCompleteListener { task ->
if (task.isSuccessful) {
lightsLiveData.observe(this, lightsDataObserver)
} else {
Timber.e(task.exception, "FirebaseAuth:failed")
// Mobile Activity
override fun onCreate(savedInstanceState: Bundle?) {
...
toggleButton.setOnCheckedChangeListener({ _, state: Boolean ->
databaseReference.child("light").setValue(state)
})
}
Nearby
● Pub/Sub
● Send messages, files or stream data
● No need for server
● Peer to peer
● Wifi or BLE
Nearby
googleApiClient = GoogleApiClient.Builder(this)
.addApi(Nearby.CONNECTIONS_API)
.addConnectionCallbacks(object :
GoogleApiClient.ConnectionCallbacks {
override fun onConnected(connectionHint: Bundle?) {
startService()
}
override fun onConnectionSuspended(cause: Int) {
failed()
}
})
.build()
private fun startService() { // Android Things
Nearby.Connections.startAdvertising(
googleApiClient,
"appName",
"serviceId",
connectionLifecycleCallback,
AdvertisingOptions(Strategy.P2P_STAR))
.setResultCallback { result ->
when {
result.status.isSuccess ->
Timber.d("startAdvertising:onResult: SUCCESS")
else -> Timber.w("STATE_READY")
private fun startService() { // Phone
Nearby.Connections.startDiscovery(
googleApiClient,
"serviceId",
endpointDiscoveryCallback,
DiscoveryOptions(Strategy.P2P_STAR))
.setResultCallback { result ->
when {
result.status.isSuccess ->
Timber.d("startDiscovery:SUCCESS")
else -> {
Timber.w("startDiscovery:FAILURE
${result.statusMessage}")
private val connectionLifecycleCallback = object :
ConnectionLifecycleCallback() {
override fun onConnectionResult(endpointId: String?, result:
ConnectionResolution?) {
Timber.d("connectionResult from " + endpointId, result)
sendDataPayload()
}
}
// Phone
private fun sendDataPayload(email : String, password: String) {
val credentials = Credentials(email, password)
val adapter = moshi.adapter(Credentials::class.java)
val json = adapter.toJson(credentials)
Nearby.Connections.sendPayload(
googleApiClient,
currentEndpointId,
Payload.fromBytes(json.toByteArray())
)
}
private val payloadCallback = object : PayloadCallback() {
override fun onPayloadReceived(endpointId: String?, payload:
Payload?) {
val adapter = moshi.adapter(Credentials::class.java)
val credentials = adapter.fromJson(jsonString)
credentials?.let {
saveCredentials(credentials)
}
}
}
firebaseAuth.signInWithEmailAndPassword(email,password)
.addOnFailureListener { exception ->
exception.printStackTrace()
}
.addOnSuccessListener {
loadData()
}
}
Success!!
https://github.com/jamescoggan/thingspresentationn
● Common code in shared module
● Nearby
● RainbowHat:
○ Sensors
○ Led
○ Button
● Philips Hue (in progress)
Q&A
sli.do
#thingstelaviv
Feedback:
https://goo.gl/gwPxpY
Thank you!
https://jamescoggan.com
@mad_team

More Related Content

What's hot

Kotlin: a better Java
Kotlin: a better JavaKotlin: a better Java
Kotlin: a better Java
Nils Breunese
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
Muhammad Abdullah
 
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan s.r.o.
 
Kotlin intro
Kotlin introKotlin intro
Kotlin intro
Elifarley Cruz
 
ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
Domenic Denicola
 
Kotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is comingKotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is coming
Kirill Rozov
 
Kotlin, why?
Kotlin, why?Kotlin, why?
Kotlin, why?
Paweł Byszewski
 
Mastering Kotlin Standard Library
Mastering Kotlin Standard LibraryMastering Kotlin Standard Library
Mastering Kotlin Standard Library
Nelson Glauber Leal
 
Java final project of scientific calcultor
Java final project of scientific calcultorJava final project of scientific calcultor
Java final project of scientific calcultor
Md. Eunus Ali Rupom
 
Advanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptAdvanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScript
ecker
 
Kotlin
KotlinKotlin
Kotlin
Rory Preddy
 
JavaScript ∩ WebAssembly
JavaScript ∩ WebAssemblyJavaScript ∩ WebAssembly
JavaScript ∩ WebAssembly
Tadeu Zagallo
 
Realm - Phoenix Mobile Festival
Realm - Phoenix Mobile FestivalRealm - Phoenix Mobile Festival
Realm - Phoenix Mobile Festival
DJ Rausch
 
Don't do this
Don't do thisDon't do this
Don't do this
Richard Jones
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
Manoj Kumar
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Languageintelliyole
 
GR8Conf 2011: GPars
GR8Conf 2011: GParsGR8Conf 2011: GPars
GR8Conf 2011: GParsGR8Conf
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.
boyney123
 
AST Transformations
AST TransformationsAST Transformations
AST TransformationsHamletDRC
 

What's hot (20)

Kotlin: a better Java
Kotlin: a better JavaKotlin: a better Java
Kotlin: a better Java
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
 
Kotlin intro
Kotlin introKotlin intro
Kotlin intro
 
ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
 
Kotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is comingKotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is coming
 
Kotlin, why?
Kotlin, why?Kotlin, why?
Kotlin, why?
 
Mastering Kotlin Standard Library
Mastering Kotlin Standard LibraryMastering Kotlin Standard Library
Mastering Kotlin Standard Library
 
Java final project of scientific calcultor
Java final project of scientific calcultorJava final project of scientific calcultor
Java final project of scientific calcultor
 
Advanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptAdvanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScript
 
Kotlin
KotlinKotlin
Kotlin
 
JavaScript ∩ WebAssembly
JavaScript ∩ WebAssemblyJavaScript ∩ WebAssembly
JavaScript ∩ WebAssembly
 
Realm - Phoenix Mobile Festival
Realm - Phoenix Mobile FestivalRealm - Phoenix Mobile Festival
Realm - Phoenix Mobile Festival
 
Don't do this
Don't do thisDon't do this
Don't do this
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
 
GR8Conf 2011: GPars
GR8Conf 2011: GParsGR8Conf 2011: GPars
GR8Conf 2011: GPars
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
 

Similar to Connecting your phone and home with firebase and android things - James Coggan, MyDrive

This is Java,I am currently stumped on how to add a scoreboard for.pdf
This is Java,I am currently stumped on how to add a scoreboard for.pdfThis is Java,I am currently stumped on how to add a scoreboard for.pdf
This is Java,I am currently stumped on how to add a scoreboard for.pdf
anjandavid
 
Android Things
Android ThingsAndroid Things
Android Things
Egor Andreevich
 
Firefox OS, fixing the mobile web - FITC Toronto - 2014-04-28
Firefox OS, fixing the mobile web - FITC Toronto - 2014-04-28Firefox OS, fixing the mobile web - FITC Toronto - 2014-04-28
Firefox OS, fixing the mobile web - FITC Toronto - 2014-04-28
Frédéric Harper
 
Firefox OS, HTML5 to the next level - Python Montreal - 2014-05-12
Firefox OS, HTML5 to the next level - Python Montreal - 2014-05-12Firefox OS, HTML5 to the next level - Python Montreal - 2014-05-12
Firefox OS, HTML5 to the next level - Python Montreal - 2014-05-12
Frédéric Harper
 
20180721 code defragment
20180721 code defragment20180721 code defragment
20180721 code defragment
Chiwon Song
 
Scientific calcultor-Java
Scientific calcultor-JavaScientific calcultor-Java
Scientific calcultor-Java
Shaibal Ahmed
 
HTML pour le web mobile, Firefox OS - Devfest Nantes - 2014-11-07
HTML pour le web mobile, Firefox OS - Devfest Nantes - 2014-11-07HTML pour le web mobile, Firefox OS - Devfest Nantes - 2014-11-07
HTML pour le web mobile, Firefox OS - Devfest Nantes - 2014-11-07Frédéric Harper
 
Matching Game In Java
Matching Game In JavaMatching Game In Java
Matching Game In Java
cmkandemir
 
Денис Ковалев «Python в игровой индустрии»
Денис Ковалев «Python в игровой индустрии»Денис Ковалев «Python в игровой индустрии»
Денис Ковалев «Python в игровой индустрии»
DataArt
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
Thierry Wasylczenko
 
Firefox OS, une plateforme à découvrir - IO Saglac - 2014-09-09
Firefox OS, une plateforme à découvrir - IO Saglac - 2014-09-09Firefox OS, une plateforme à découvrir - IO Saglac - 2014-09-09
Firefox OS, une plateforme à découvrir - IO Saglac - 2014-09-09
Frédéric Harper
 
Performance #1: Memory
Performance #1: MemoryPerformance #1: Memory
Performance #1: Memory
Yonatan Levin
 
State management in android applications
State management in android applicationsState management in android applications
State management in android applications
Gabor Varadi
 
Html5 game, websocket e arduino
Html5 game, websocket e arduino Html5 game, websocket e arduino
Html5 game, websocket e arduino Giuseppe Modarelli
 
Html5 game, websocket e arduino
Html5 game, websocket e arduinoHtml5 game, websocket e arduino
Html5 game, websocket e arduino
monksoftwareit
 
The next step, part 2
The next step, part 2The next step, part 2
The next step, part 2
Pat Cavit
 
mobl
moblmobl
mobl
zefhemel
 
Voice-enabling Your Home and Devices with Amazon Alexa and AWS IoT - Level 200
Voice-enabling Your Home and Devices with Amazon Alexa and AWS IoT - Level 200Voice-enabling Your Home and Devices with Amazon Alexa and AWS IoT - Level 200
Voice-enabling Your Home and Devices with Amazon Alexa and AWS IoT - Level 200
Amazon Web Services
 
HTML for the Mobile Web, Firefox OS - All Things Open - 2014-10-22
HTML for the Mobile Web, Firefox OS - All Things Open - 2014-10-22HTML for the Mobile Web, Firefox OS - All Things Open - 2014-10-22
HTML for the Mobile Web, Firefox OS - All Things Open - 2014-10-22
Frédéric Harper
 

Similar to Connecting your phone and home with firebase and android things - James Coggan, MyDrive (20)

Android workshop
Android workshopAndroid workshop
Android workshop
 
This is Java,I am currently stumped on how to add a scoreboard for.pdf
This is Java,I am currently stumped on how to add a scoreboard for.pdfThis is Java,I am currently stumped on how to add a scoreboard for.pdf
This is Java,I am currently stumped on how to add a scoreboard for.pdf
 
Android Things
Android ThingsAndroid Things
Android Things
 
Firefox OS, fixing the mobile web - FITC Toronto - 2014-04-28
Firefox OS, fixing the mobile web - FITC Toronto - 2014-04-28Firefox OS, fixing the mobile web - FITC Toronto - 2014-04-28
Firefox OS, fixing the mobile web - FITC Toronto - 2014-04-28
 
Firefox OS, HTML5 to the next level - Python Montreal - 2014-05-12
Firefox OS, HTML5 to the next level - Python Montreal - 2014-05-12Firefox OS, HTML5 to the next level - Python Montreal - 2014-05-12
Firefox OS, HTML5 to the next level - Python Montreal - 2014-05-12
 
20180721 code defragment
20180721 code defragment20180721 code defragment
20180721 code defragment
 
Scientific calcultor-Java
Scientific calcultor-JavaScientific calcultor-Java
Scientific calcultor-Java
 
HTML pour le web mobile, Firefox OS - Devfest Nantes - 2014-11-07
HTML pour le web mobile, Firefox OS - Devfest Nantes - 2014-11-07HTML pour le web mobile, Firefox OS - Devfest Nantes - 2014-11-07
HTML pour le web mobile, Firefox OS - Devfest Nantes - 2014-11-07
 
Matching Game In Java
Matching Game In JavaMatching Game In Java
Matching Game In Java
 
Денис Ковалев «Python в игровой индустрии»
Денис Ковалев «Python в игровой индустрии»Денис Ковалев «Python в игровой индустрии»
Денис Ковалев «Python в игровой индустрии»
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
Firefox OS, une plateforme à découvrir - IO Saglac - 2014-09-09
Firefox OS, une plateforme à découvrir - IO Saglac - 2014-09-09Firefox OS, une plateforme à découvrir - IO Saglac - 2014-09-09
Firefox OS, une plateforme à découvrir - IO Saglac - 2014-09-09
 
Performance #1: Memory
Performance #1: MemoryPerformance #1: Memory
Performance #1: Memory
 
State management in android applications
State management in android applicationsState management in android applications
State management in android applications
 
Html5 game, websocket e arduino
Html5 game, websocket e arduino Html5 game, websocket e arduino
Html5 game, websocket e arduino
 
Html5 game, websocket e arduino
Html5 game, websocket e arduinoHtml5 game, websocket e arduino
Html5 game, websocket e arduino
 
The next step, part 2
The next step, part 2The next step, part 2
The next step, part 2
 
mobl
moblmobl
mobl
 
Voice-enabling Your Home and Devices with Amazon Alexa and AWS IoT - Level 200
Voice-enabling Your Home and Devices with Amazon Alexa and AWS IoT - Level 200Voice-enabling Your Home and Devices with Amazon Alexa and AWS IoT - Level 200
Voice-enabling Your Home and Devices with Amazon Alexa and AWS IoT - Level 200
 
HTML for the Mobile Web, Firefox OS - All Things Open - 2014-10-22
HTML for the Mobile Web, Firefox OS - All Things Open - 2014-10-22HTML for the Mobile Web, Firefox OS - All Things Open - 2014-10-22
HTML for the Mobile Web, Firefox OS - All Things Open - 2014-10-22
 

More from DroidConTLV

Mobile Development in the Information Age - Yossi Elkrief, Nike
Mobile Development in the Information Age - Yossi Elkrief, NikeMobile Development in the Information Age - Yossi Elkrief, Nike
Mobile Development in the Information Age - Yossi Elkrief, Nike
DroidConTLV
 
Doing work in the background - Darryn Campbell, Zebra Technologies
Doing work in the background - Darryn Campbell, Zebra TechnologiesDoing work in the background - Darryn Campbell, Zebra Technologies
Doing work in the background - Darryn Campbell, Zebra Technologies
DroidConTLV
 
No more video loss - Alex Rivkin, Motorola Solutions
No more video loss - Alex Rivkin, Motorola SolutionsNo more video loss - Alex Rivkin, Motorola Solutions
No more video loss - Alex Rivkin, Motorola Solutions
DroidConTLV
 
Mobile at Scale: from startup to a big company - Dor Samet, Booking.com
Mobile at Scale: from startup to a big company - Dor Samet, Booking.comMobile at Scale: from startup to a big company - Dor Samet, Booking.com
Mobile at Scale: from startup to a big company - Dor Samet, Booking.com
DroidConTLV
 
LiveData on Steroids - Giora Shevach + Shahar Ben Moshe, Climacell
LiveData on Steroids - Giora Shevach + Shahar Ben Moshe, ClimacellLiveData on Steroids - Giora Shevach + Shahar Ben Moshe, Climacell
LiveData on Steroids - Giora Shevach + Shahar Ben Moshe, Climacell
DroidConTLV
 
MVVM In real life - Lea Cohen Tannoudji, Lightricks
MVVM In real life - Lea Cohen Tannoudji, LightricksMVVM In real life - Lea Cohen Tannoudji, Lightricks
MVVM In real life - Lea Cohen Tannoudji, Lightricks
DroidConTLV
 
Best Practices for Using Mobile SDKs - Lilach Wagner, SafeDK (AppLovin)
Best Practices for Using Mobile SDKs - Lilach Wagner, SafeDK (AppLovin)Best Practices for Using Mobile SDKs - Lilach Wagner, SafeDK (AppLovin)
Best Practices for Using Mobile SDKs - Lilach Wagner, SafeDK (AppLovin)
DroidConTLV
 
Building Apps with Flutter - Hillel Coren, Invoice Ninja
Building Apps with Flutter - Hillel Coren, Invoice NinjaBuilding Apps with Flutter - Hillel Coren, Invoice Ninja
Building Apps with Flutter - Hillel Coren, Invoice Ninja
DroidConTLV
 
New Android Project: The Most Important Decisions - Vasiliy Zukanov
New Android Project: The Most Important Decisions - Vasiliy ZukanovNew Android Project: The Most Important Decisions - Vasiliy Zukanov
New Android Project: The Most Important Decisions - Vasiliy Zukanov
DroidConTLV
 
Designing a Design System - Shai Mishali, Gett
Designing a Design System - Shai Mishali, GettDesigning a Design System - Shai Mishali, Gett
Designing a Design System - Shai Mishali, Gett
DroidConTLV
 
The Mighty Power of the Accessibility Service - Guy Griv, Pepper
The Mighty Power of the Accessibility Service - Guy Griv, PepperThe Mighty Power of the Accessibility Service - Guy Griv, Pepper
The Mighty Power of the Accessibility Service - Guy Griv, Pepper
DroidConTLV
 
Kotlin Multiplatform in Action - Alexandr Pogrebnyak - IceRockDev
Kotlin Multiplatform in Action - Alexandr Pogrebnyak - IceRockDevKotlin Multiplatform in Action - Alexandr Pogrebnyak - IceRockDev
Kotlin Multiplatform in Action - Alexandr Pogrebnyak - IceRockDev
DroidConTLV
 
Flutter State Management - Moti Bartov, Tikal
Flutter State Management - Moti Bartov, TikalFlutter State Management - Moti Bartov, Tikal
Flutter State Management - Moti Bartov, Tikal
DroidConTLV
 
Reactive UI in android - Gil Goldzweig Goldbaum, 10bis
Reactive UI in android - Gil Goldzweig Goldbaum, 10bisReactive UI in android - Gil Goldzweig Goldbaum, 10bis
Reactive UI in android - Gil Goldzweig Goldbaum, 10bis
DroidConTLV
 
Fun with flutter animations - Divyanshu Bhargava, GoHighLevel
Fun with flutter animations - Divyanshu Bhargava, GoHighLevelFun with flutter animations - Divyanshu Bhargava, GoHighLevel
Fun with flutter animations - Divyanshu Bhargava, GoHighLevel
DroidConTLV
 
DroidconTLV 2019
DroidconTLV 2019DroidconTLV 2019
DroidconTLV 2019
DroidConTLV
 
Ok google, it's time to bot! - Hadar Franco, Albert + Stav Levi, Monday
Ok google, it's time to bot! - Hadar Franco, Albert + Stav Levi, MondayOk google, it's time to bot! - Hadar Franco, Albert + Stav Levi, Monday
Ok google, it's time to bot! - Hadar Franco, Albert + Stav Levi, Monday
DroidConTLV
 
Introduction to React Native - Lev Vidrak, Wix
Introduction to React Native - Lev Vidrak, WixIntroduction to React Native - Lev Vidrak, Wix
Introduction to React Native - Lev Vidrak, Wix
DroidConTLV
 
Bang-Bang, you have been hacked - Yonatan Levin, KolGene
Bang-Bang, you have been hacked - Yonatan Levin, KolGeneBang-Bang, you have been hacked - Yonatan Levin, KolGene
Bang-Bang, you have been hacked - Yonatan Levin, KolGene
DroidConTLV
 
Educating your app – adding ML edge to your apps - Maoz Tamir
Educating your app – adding ML edge to your apps - Maoz TamirEducating your app – adding ML edge to your apps - Maoz Tamir
Educating your app – adding ML edge to your apps - Maoz Tamir
DroidConTLV
 

More from DroidConTLV (20)

Mobile Development in the Information Age - Yossi Elkrief, Nike
Mobile Development in the Information Age - Yossi Elkrief, NikeMobile Development in the Information Age - Yossi Elkrief, Nike
Mobile Development in the Information Age - Yossi Elkrief, Nike
 
Doing work in the background - Darryn Campbell, Zebra Technologies
Doing work in the background - Darryn Campbell, Zebra TechnologiesDoing work in the background - Darryn Campbell, Zebra Technologies
Doing work in the background - Darryn Campbell, Zebra Technologies
 
No more video loss - Alex Rivkin, Motorola Solutions
No more video loss - Alex Rivkin, Motorola SolutionsNo more video loss - Alex Rivkin, Motorola Solutions
No more video loss - Alex Rivkin, Motorola Solutions
 
Mobile at Scale: from startup to a big company - Dor Samet, Booking.com
Mobile at Scale: from startup to a big company - Dor Samet, Booking.comMobile at Scale: from startup to a big company - Dor Samet, Booking.com
Mobile at Scale: from startup to a big company - Dor Samet, Booking.com
 
LiveData on Steroids - Giora Shevach + Shahar Ben Moshe, Climacell
LiveData on Steroids - Giora Shevach + Shahar Ben Moshe, ClimacellLiveData on Steroids - Giora Shevach + Shahar Ben Moshe, Climacell
LiveData on Steroids - Giora Shevach + Shahar Ben Moshe, Climacell
 
MVVM In real life - Lea Cohen Tannoudji, Lightricks
MVVM In real life - Lea Cohen Tannoudji, LightricksMVVM In real life - Lea Cohen Tannoudji, Lightricks
MVVM In real life - Lea Cohen Tannoudji, Lightricks
 
Best Practices for Using Mobile SDKs - Lilach Wagner, SafeDK (AppLovin)
Best Practices for Using Mobile SDKs - Lilach Wagner, SafeDK (AppLovin)Best Practices for Using Mobile SDKs - Lilach Wagner, SafeDK (AppLovin)
Best Practices for Using Mobile SDKs - Lilach Wagner, SafeDK (AppLovin)
 
Building Apps with Flutter - Hillel Coren, Invoice Ninja
Building Apps with Flutter - Hillel Coren, Invoice NinjaBuilding Apps with Flutter - Hillel Coren, Invoice Ninja
Building Apps with Flutter - Hillel Coren, Invoice Ninja
 
New Android Project: The Most Important Decisions - Vasiliy Zukanov
New Android Project: The Most Important Decisions - Vasiliy ZukanovNew Android Project: The Most Important Decisions - Vasiliy Zukanov
New Android Project: The Most Important Decisions - Vasiliy Zukanov
 
Designing a Design System - Shai Mishali, Gett
Designing a Design System - Shai Mishali, GettDesigning a Design System - Shai Mishali, Gett
Designing a Design System - Shai Mishali, Gett
 
The Mighty Power of the Accessibility Service - Guy Griv, Pepper
The Mighty Power of the Accessibility Service - Guy Griv, PepperThe Mighty Power of the Accessibility Service - Guy Griv, Pepper
The Mighty Power of the Accessibility Service - Guy Griv, Pepper
 
Kotlin Multiplatform in Action - Alexandr Pogrebnyak - IceRockDev
Kotlin Multiplatform in Action - Alexandr Pogrebnyak - IceRockDevKotlin Multiplatform in Action - Alexandr Pogrebnyak - IceRockDev
Kotlin Multiplatform in Action - Alexandr Pogrebnyak - IceRockDev
 
Flutter State Management - Moti Bartov, Tikal
Flutter State Management - Moti Bartov, TikalFlutter State Management - Moti Bartov, Tikal
Flutter State Management - Moti Bartov, Tikal
 
Reactive UI in android - Gil Goldzweig Goldbaum, 10bis
Reactive UI in android - Gil Goldzweig Goldbaum, 10bisReactive UI in android - Gil Goldzweig Goldbaum, 10bis
Reactive UI in android - Gil Goldzweig Goldbaum, 10bis
 
Fun with flutter animations - Divyanshu Bhargava, GoHighLevel
Fun with flutter animations - Divyanshu Bhargava, GoHighLevelFun with flutter animations - Divyanshu Bhargava, GoHighLevel
Fun with flutter animations - Divyanshu Bhargava, GoHighLevel
 
DroidconTLV 2019
DroidconTLV 2019DroidconTLV 2019
DroidconTLV 2019
 
Ok google, it's time to bot! - Hadar Franco, Albert + Stav Levi, Monday
Ok google, it's time to bot! - Hadar Franco, Albert + Stav Levi, MondayOk google, it's time to bot! - Hadar Franco, Albert + Stav Levi, Monday
Ok google, it's time to bot! - Hadar Franco, Albert + Stav Levi, Monday
 
Introduction to React Native - Lev Vidrak, Wix
Introduction to React Native - Lev Vidrak, WixIntroduction to React Native - Lev Vidrak, Wix
Introduction to React Native - Lev Vidrak, Wix
 
Bang-Bang, you have been hacked - Yonatan Levin, KolGene
Bang-Bang, you have been hacked - Yonatan Levin, KolGeneBang-Bang, you have been hacked - Yonatan Levin, KolGene
Bang-Bang, you have been hacked - Yonatan Levin, KolGene
 
Educating your app – adding ML edge to your apps - Maoz Tamir
Educating your app – adding ML edge to your apps - Maoz TamirEducating your app – adding ML edge to your apps - Maoz Tamir
Educating your app – adding ML edge to your apps - Maoz Tamir
 

Recently uploaded

PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 

Recently uploaded (20)

PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 

Connecting your phone and home with firebase and android things - James Coggan, MyDrive

  • 1. James Coggan, MyDrive Solutions Connect your Phone and Home with Firebase and Android Things We are hiring! https://www.mydrivesolutions.com/jobs Q&A sli.do #thingstelaviv
  • 2. A little bit about me.. James Coggan Android tech lead https://jamescoggan.com @mad_team
  • 3.
  • 4. What is Android Things?
  • 5. Android + Internet of ThingsAndroid Things
  • 6. The hardware NXP Pico i.MX7D Raspberry Pi 3 NXP Argon i.MX6UL NXP Pico i.MX6UL
  • 7. Development kits NXP Pico i.MX7D Raspberry pi kit
  • 10. What Android Things does support
  • 11. What Android Things doesn’t support
  • 12. Good to know ● Main application started on boot ● Permissions are free and set on reboot ● adb connect 192.168.1.111:5555
  • 13. Why Android Things? ● Kotlin :) ● Maintained by Google ● OTA updates ● Android community ● Hardware agnostic ● Relatively cheap hardware ● Reusable code
  • 17. 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)
  • 18.
  • 19.
  • 21. val pioService = PeripheralManagerService() try { val pinName = "BCM6" ledGpio = pioService.openGpio(pinName) ledGpio?.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW) } catch (e: IOException) { e.printStackTrace() }
  • 22. val pioService = PeripheralManagerService() try { val pinName = "BCM21" button = ButtonInputDriver( pinName, Button.LogicState.PRESSED_WHEN_LOW, KeyEvent.KEYCODE_SPACE) button?.register() } catch (e: IOException) { e.printStackTrace() }
  • 23. override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { if (keyCode == KeyEvent.KEYCODE_SPACE) { setLedValue(true) return true } return super.onKeyDown(keyCode, event) }
  • 24. override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean { if (keyCode == KeyEvent.KEYCODE_SPACE) { setLedValue(false) return true } return super.onKeyUp(keyCode, event) }
  • 25. 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) } }
  • 26. 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) } }
  • 27. val pinName = gpioForLED ledGpio = pioService.openGpio(pinName) ... val pinName = gpioForButton button = ButtonInputDriver( pinName, Button.LogicState.PRESSED_WHEN_LOW, KeyEvent.KEYCODE_SPACE) ...
  • 28.
  • 29.
  • 30.
  • 31. 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: ie: com.jamescoggan.thingspresentation ● Enable anonymous login on (temporarily)
  • 32. ● Setup a database // Database { "light" : true } ● Add the rules // Rules - don’t expose your data for the world { "rules": { ".write": "auth != null", ".read": "auth != null", } }
  • 33. // Base build.gradle for all modules buildscript { ... dependencies { classpath "com.google.gms:google-services:$googleServicesClassVersion" } }
  • 34. // mobile & things build.gradle dependencies { ... implementation "com.google.firebase:firebase-core:$playServicesVersion" implementation "com.google.firebase:firebase-database:$playServicesVersion" implementation "com.google.firebase:firebase-auth:$playServicesVersion" implementation "android.arch.lifecycle:extensions:$androidArchComponentsVersion" } apply plugin: "com.google.gms.google-services"
  • 35. // MainActivity.kt (Both modules - mobile and things) override fun onCreate(savedInstanceState: Bundle?) { FirebaseApp.initializeApp(this) // Move me to the Application class val firebaseAuth = FirebaseAuth.getInstance() val databaseReference = FirebaseDatabase.getInstance().reference }
  • 36. // MainActivity.kt override fun onCreate(savedInstanceState: Bundle?) { ... val databaseReference = FirebaseDatabase.getInstance().reference firebaseAuth.signInAnonymously() .addOnCompleteListener { task -> if (task.isSuccessful) { observeLightsData() } else { Timber.e(task.exception, "FirebaseAuth:failed") } } }
  • 37. // Light.kt class FirebaseTables { companion object { val LIGHTS_BASE = "light" } } data class Light(val light : Boolean)
  • 38. class LightLiveData(val firebase: DatabaseReference) : LiveData<Light>() { private val valueEventListener = object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { val newValue = snapshot.getValue(Boolean::class.java) ?: false value = Light(newValue) } override fun onCancelled(error: DatabaseError) { } } override fun onActive() { firebase.child(LIGHTS_BASE).addValueEventListener(valueEventListener) } override fun onInactive() { firebase.child(LIGHTS_BASE).removeEventListener(valueEventListener) } }
  • 39. // Things Activity private val lightsDataObserver = Observer<Light> { lightState -> Timber.d("LightState changed: ${lightState?.isOn}") led.setValue(lightState?.isOn ?: false) } override fun onCreate(savedInstanceState: Bundle?) { ... firebaseAuth.signInAnonymously() .addOnCompleteListener { task -> if (task.isSuccessful) { lightsLiveData.observe(this, lightsDataObserver) } else { Timber.e(task.exception, "FirebaseAuth:failed")
  • 40. // Mobile Activity override fun onCreate(savedInstanceState: Bundle?) { ... toggleButton.setOnCheckedChangeListener({ _, state: Boolean -> databaseReference.child("light").setValue(state) }) }
  • 41.
  • 42.
  • 43.
  • 44. Nearby ● Pub/Sub ● Send messages, files or stream data ● No need for server ● Peer to peer ● Wifi or BLE
  • 46. googleApiClient = GoogleApiClient.Builder(this) .addApi(Nearby.CONNECTIONS_API) .addConnectionCallbacks(object : GoogleApiClient.ConnectionCallbacks { override fun onConnected(connectionHint: Bundle?) { startService() } override fun onConnectionSuspended(cause: Int) { failed() } }) .build()
  • 47. private fun startService() { // Android Things Nearby.Connections.startAdvertising( googleApiClient, "appName", "serviceId", connectionLifecycleCallback, AdvertisingOptions(Strategy.P2P_STAR)) .setResultCallback { result -> when { result.status.isSuccess -> Timber.d("startAdvertising:onResult: SUCCESS") else -> Timber.w("STATE_READY")
  • 48. private fun startService() { // Phone Nearby.Connections.startDiscovery( googleApiClient, "serviceId", endpointDiscoveryCallback, DiscoveryOptions(Strategy.P2P_STAR)) .setResultCallback { result -> when { result.status.isSuccess -> Timber.d("startDiscovery:SUCCESS") else -> { Timber.w("startDiscovery:FAILURE ${result.statusMessage}")
  • 49. private val connectionLifecycleCallback = object : ConnectionLifecycleCallback() { override fun onConnectionResult(endpointId: String?, result: ConnectionResolution?) { Timber.d("connectionResult from " + endpointId, result) sendDataPayload() } }
  • 50. // Phone private fun sendDataPayload(email : String, password: String) { val credentials = Credentials(email, password) val adapter = moshi.adapter(Credentials::class.java) val json = adapter.toJson(credentials) Nearby.Connections.sendPayload( googleApiClient, currentEndpointId, Payload.fromBytes(json.toByteArray()) ) }
  • 51. private val payloadCallback = object : PayloadCallback() { override fun onPayloadReceived(endpointId: String?, payload: Payload?) { val adapter = moshi.adapter(Credentials::class.java) val credentials = adapter.fromJson(jsonString) credentials?.let { saveCredentials(credentials) } } }
  • 52. firebaseAuth.signInWithEmailAndPassword(email,password) .addOnFailureListener { exception -> exception.printStackTrace() } .addOnSuccessListener { loadData() } }
  • 54. https://github.com/jamescoggan/thingspresentationn ● Common code in shared module ● Nearby ● RainbowHat: ○ Sensors ○ Led ○ Button ● Philips Hue (in progress)