SlideShare uma empresa Scribd logo
1 de 56
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
intelliyole
 
GR8Conf 2011: GPars
GR8Conf 2011: GParsGR8Conf 2011: GPars
GR8Conf 2011: GPars
GR8Conf
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
HamletDRC
 

Mais procurados (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
 

Semelhante a 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
 
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
Frédéric Harper
 
Html5 game, websocket e arduino
Html5 game, websocket e arduino Html5 game, websocket e arduino
Html5 game, websocket e arduino
Giuseppe Modarelli
 

Semelhante a 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
 

Mais de DroidConTLV

Mais de 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
 

Último

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 

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)