├── .gitignore
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── app
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── hyperaware
│ │ └── doorbell
│ │ └── app
│ │ ├── activity
│ │ ├── AnswerRingActivity.kt
│ │ ├── ListRingsActivity.kt
│ │ ├── MainActivity.kt
│ │ ├── NearbyConnectionsActivity.kt
│ │ └── NearbyMessagingActivity.kt
│ │ ├── fcm
│ │ ├── MyInstanceIdService.kt
│ │ └── OnRingMessagingService.kt
│ │ ├── glide
│ │ └── FirebaseStorageGlideModule.kt
│ │ └── model
│ │ └── Ring.kt
│ └── res
│ ├── drawable-hdpi
│ ├── ic_check_black_24dp.png
│ ├── ic_do_not_disturb_black_24dp.png
│ └── ic_face_black_24dp.png
│ ├── drawable-mdpi
│ ├── ic_check_black_24dp.png
│ ├── ic_do_not_disturb_black_24dp.png
│ └── ic_face_black_24dp.png
│ ├── drawable-v24
│ └── ic_launcher_foreground.xml
│ ├── drawable-xhdpi
│ ├── ic_check_black_24dp.png
│ ├── ic_do_not_disturb_black_24dp.png
│ └── ic_face_black_24dp.png
│ ├── drawable-xxhdpi
│ ├── ic_check_black_24dp.png
│ ├── ic_do_not_disturb_black_24dp.png
│ └── ic_face_black_24dp.png
│ ├── drawable-xxxhdpi
│ ├── ic_check_black_24dp.png
│ ├── ic_do_not_disturb_black_24dp.png
│ └── ic_face_black_24dp.png
│ ├── drawable
│ └── ic_launcher_background.xml
│ ├── layout
│ ├── activity_answer.xml
│ ├── activity_auth.xml
│ ├── activity_list_rings.xml
│ ├── activity_main.xml
│ ├── content_list_rings.xml
│ └── ring_item.xml
│ ├── mipmap-anydpi-v26
│ ├── ic_launcher.xml
│ └── ic_launcher_round.xml
│ ├── mipmap-hdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-mdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-xhdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-xxhdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-xxxhdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ └── values
│ ├── colors.xml
│ ├── dimens.xml
│ ├── strings.xml
│ └── styles.xml
├── backend
├── .firebaserc
├── .gitignore
├── firebase.json
├── firestore.indexes.json
├── firestore.rules
├── functions
│ ├── .gitignore
│ ├── package-lock.json
│ ├── package.json
│ ├── src
│ │ └── index.ts
│ ├── tsconfig.json
│ └── tslint.json
├── scripts
│ └── config-env.sh
└── storage.rules
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── thing
├── build.gradle
├── proguard-rules.pro
└── src
├── fakeThing
└── java
│ └── com
│ └── hyperaware
│ └── doorbell
│ └── thing
│ └── activity
│ └── MainActivity.kt
├── main
├── AndroidManifest.xml
├── java
│ └── com
│ │ └── hyperaware
│ │ └── doorbell
│ │ └── thing
│ │ ├── activity
│ │ ├── AutoFitSurfaceView.kt
│ │ ├── BaseMainActivity.kt
│ │ ├── Camera2Activity.kt
│ │ ├── Camera2BasicFragment.kt
│ │ ├── CountdownTimer.kt
│ │ ├── NearbyConnectionsActivity.kt
│ │ ├── NearbyMessagingActivity.kt
│ │ ├── ResponseActivity.kt
│ │ └── TestMainActivity.kt
│ │ └── fcm
│ │ ├── MyInstanceIdService.kt
│ │ └── OnAnswerMessagingService.kt
└── res
│ ├── layout
│ ├── activity_auth.xml
│ ├── activity_camera.xml
│ ├── activity_response.xml
│ ├── activity_test_main.xml
│ ├── camera.xml
│ ├── fragment_camera2_basic.xml
│ ├── main.xml
│ └── thing.xml
│ └── values
│ ├── colors.xml
│ ├── strings.xml
│ └── styles.xml
└── realThing
├── AndroidManifest.xml
└── java
└── com
└── hyperaware
└── doorbell
└── thing
└── activity
└── MainActivity.kt
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | /.gradle
3 | /local.properties
4 | /.idea
5 | .DS_Store
6 | /build
7 | /*/build
8 | /*/google-services.json
9 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # How to Contribute
2 |
3 | We'd love to accept your patches and contributions to this project. There are
4 | just a few small guidelines you need to follow.
5 |
6 | ## Contributor License Agreement
7 |
8 | Contributions to this project must be accompanied by a Contributor License
9 | Agreement. You (or your employer) retain the copyright to your contribution;
10 | this simply gives us permission to use and redistribute your contributions as
11 | part of the project. Head over to to see
12 | your current agreements on file or to sign a new one.
13 |
14 | You generally only need to submit a CLA once, so if you've already submitted one
15 | (even if it was for a different project), you probably don't need to do it
16 | again.
17 |
18 | ## Code reviews
19 |
20 | All submissions, including submissions by project members, require review. We
21 | use GitHub pull requests for this purpose. Consult
22 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more
23 | information on using pull requests.
24 |
25 | ## Community Guidelines
26 |
27 | This project follows [Google's Open Source Community
28 | Guidelines](https://opensource.google.com/conduct/).
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Firebase Doorbell
2 |
3 | This is a demo project for a home appliance video doorbell implemented for
4 | Android Things with Firebase. It's also the subject of my talk "[Connect
5 | your Android Things with Firebase][1]".
6 |
7 | There are three components to this project:
8 |
9 | - An Android Things app (the doorbell)
10 | - A companion app (homeowner app)
11 | - A backend implemented with Cloud Functions
12 |
13 | The Android Things app lives under "thing", and the companion app lives
14 | under "app". They both need to be added as apps to a Firebase project.
15 | The backend lives under "backend" and should be deployed to the same project
16 | with the Firebase CLI.
17 |
18 | The latest version of the slides of the related talk can be found on
19 | [SpeakerDeck][1]. There are some slides with code and a helpful system
20 | diagram that shows how the following Firebase and Google APIs were used:
21 |
22 | - Cloud Firestore
23 | - Cloud Storage
24 | - Cloud Messaging
25 | - Cloud Functions
26 | - Nearby
27 |
28 | **NOTE**: A service account is required for the Cloud Functions code to
29 | run correctly. The script under `backend/scripts/config-env.sh` will help
30 | you get your service account file added as an env var to deploy with the
31 | functions.
32 |
33 | ## Watch the session
34 |
35 | Recorded at Droidcon VN:
36 |
37 | [](https://www.youtube.com/watch?v=F-zq8xOntEE)
38 |
39 | ## License
40 |
41 | The code in this project is licensed under the Apache License 2.0.
42 |
43 | ```text
44 | Copyright 2018 Google LLC
45 |
46 | Licensed under the Apache License, Version 2.0 (the "License");
47 | you may not use this file except in compliance with the License.
48 | You may obtain a copy of the License at
49 |
50 | https://www.apache.org/licenses/LICENSE-2.0
51 |
52 | Unless required by applicable law or agreed to in writing, software
53 | distributed under the License is distributed on an "AS IS" BASIS,
54 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
55 | See the License for the specific language governing permissions and
56 | limitations under the License.
57 | ```
58 |
59 | ## Disclaimer
60 |
61 | This is not an officially supported Google product.
62 |
63 | [1]: https://speakerdeck.com/codingdoug/connect-your-android-things-with-firebase-devfestdc
64 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-android-extensions'
4 | apply plugin: 'kotlin-kapt'
5 | //apply plugin: 'com.google.firebase.firebase-perf'
6 | apply plugin: 'io.fabric'
7 |
8 | android {
9 | compileSdkVersion 27
10 | defaultConfig {
11 | applicationId "com.hyperaware.doorbell.app"
12 | minSdkVersion 21
13 | targetSdkVersion 27
14 | versionCode 1
15 | versionName "1.0"
16 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
17 | resConfigs "en"
18 | }
19 | buildTypes {
20 | release {
21 | minifyEnabled false
22 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
23 | }
24 | }
25 | }
26 |
27 | dependencies {
28 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
29 |
30 | implementation "com.android.support:appcompat-v7:$android_support_version"
31 | implementation "com.android.support:cardview-v7:$android_support_version"
32 | implementation "com.android.support:customtabs:$android_support_version"
33 | implementation "com.android.support:design:$android_support_version"
34 | implementation 'com.android.support.constraint:constraint-layout:1.1.3'
35 |
36 | implementation "com.google.android.gms:play-services-nearby:$app_play_services_version"
37 | implementation "com.google.firebase:firebase-core:$app_play_services_version"
38 | implementation "com.google.firebase:firebase-auth:$app_play_services_version"
39 | implementation "com.google.firebase:firebase-firestore:$app_play_services_version"
40 | implementation "com.google.firebase:firebase-messaging:$app_play_services_version"
41 | implementation "com.google.firebase:firebase-perf:$app_play_services_version"
42 |
43 | implementation "com.firebaseui:firebase-ui-auth:$firebase_ui_version"
44 | implementation "com.firebaseui:firebase-ui-firestore:$firebase_ui_version"
45 | implementation "com.firebaseui:firebase-ui-storage:$firebase_ui_version"
46 | implementation "com.crashlytics.sdk.android:crashlytics:2.9.5"
47 |
48 | kapt "com.github.bumptech.glide:compiler:$glide_version"
49 | implementation "com.github.bumptech.glide:glide:$glide_version"
50 | }
51 |
52 | apply plugin: 'com.google.gms.google-services'
53 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | -keep public class * implements com.bumptech.glide.module.GlideModule
2 | -keep public class * extends com.bumptech.glide.module.AppGlideModule
3 | -keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** {
4 | **[] $VALUES;
5 | public *;
6 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
32 |
33 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
51 |
52 |
53 |
54 |
55 |
56 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hyperaware/doorbell/app/activity/AnswerRingActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.hyperaware.doorbell.app.activity
18 |
19 | import android.os.Bundle
20 | import android.support.v7.app.AppCompatActivity
21 | import android.util.Log
22 | import android.widget.Button
23 | import android.widget.ImageView
24 | import android.widget.Toast
25 | import com.bumptech.glide.Glide
26 | import com.google.firebase.auth.FirebaseAuth
27 | import com.google.firebase.firestore.DocumentReference
28 | import com.google.firebase.firestore.FirebaseFirestore
29 | import com.google.firebase.storage.FirebaseStorage
30 | import com.hyperaware.doorbell.app.R
31 | import com.hyperaware.doorbell.app.model.Ring
32 |
33 | class AnswerRingActivity : AppCompatActivity() {
34 |
35 | companion object {
36 | private const val TAG = "AnswerActivity"
37 | private val FIR_STORAGE = FirebaseStorage.getInstance()
38 | const val EXTRA_RING_ID = "ring_id"
39 | }
40 |
41 | private lateinit var ivGuest: ImageView
42 | private lateinit var ringReference: DocumentReference
43 | private lateinit var uid: String
44 |
45 | override fun onCreate(savedInstanceState: Bundle?) {
46 | super.onCreate(savedInstanceState)
47 | setContentView(R.layout.activity_answer)
48 |
49 | val user = FirebaseAuth.getInstance().currentUser
50 | if (user != null) {
51 | uid = user.uid
52 | }
53 | else {
54 | val msg = getString(R.string.msg_answer_ring_requires_login)
55 | Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
56 | Log.e(TAG, msg)
57 | finish()
58 | }
59 |
60 | val extras = intent.extras
61 | if (extras == null) {
62 | Log.e(TAG, "$EXTRA_RING_ID was not provided")
63 | finish()
64 | return
65 | }
66 |
67 | val ringId = extras.getString(EXTRA_RING_ID)
68 | if (ringId.isEmpty()) {
69 | Log.e(TAG, "$EXTRA_RING_ID was empty")
70 | finish()
71 | return
72 | }
73 |
74 | initViews()
75 |
76 | Log.d(TAG, "Ring id: $ringId")
77 | ringReference = FirebaseFirestore.getInstance().collection("rings").document(ringId)
78 | populateViews(ringId)
79 | }
80 |
81 | private fun initViews() {
82 | ivGuest = findViewById(R.id.iv_guest)
83 |
84 | findViewById(R.id.btn_no).setOnClickListener {
85 | updateAnswer(false)
86 | }
87 |
88 | findViewById(R.id.btn_yes).setOnClickListener {
89 | updateAnswer(true)
90 | }
91 | }
92 |
93 | private fun populateViews(ringId: String) {
94 | ringReference.get()
95 | .addOnSuccessListener(this) { snap ->
96 | if (snap.exists()) {
97 | val ring = snap.toObject(Ring::class.java)!!
98 | Log.d(TAG, "imagePath ${ring.imagePath!!}")
99 | Glide.with(this@AnswerRingActivity)
100 | .load(FIR_STORAGE.getReference(ring.imagePath!!))
101 | .into(ivGuest)
102 | }
103 | else {
104 | Log.e(TAG, "No document for ring $ringId")
105 | finish()
106 | }
107 | }
108 | .addOnFailureListener(this) { error ->
109 | Log.e(TAG, "Can't fetch ring $ringId", error)
110 | finish()
111 | }
112 | }
113 |
114 | private fun updateAnswer(disposition: Boolean) {
115 | ringReference.update(
116 | "answer.uid", uid,
117 | "answer.disposition", disposition)
118 | .addOnCompleteListener(this) {
119 | Log.d(TAG, "Answer written to database")
120 | finish()
121 | }
122 | .addOnFailureListener(this) { e ->
123 | Log.d(TAG, "Answer not written to database", e)
124 | finish()
125 | }
126 | }
127 |
128 | }
129 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hyperaware/doorbell/app/activity/ListRingsActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.hyperaware.doorbell.app.activity
18 |
19 | import android.os.Bundle
20 | import android.support.v7.app.AppCompatActivity
21 | import android.support.v7.widget.LinearLayoutManager
22 | import android.support.v7.widget.RecyclerView
23 | import android.support.v7.widget.Toolbar
24 | import android.view.LayoutInflater
25 | import android.view.View
26 | import android.view.ViewGroup
27 | import android.widget.ImageView
28 | import android.widget.TextView
29 | import com.bumptech.glide.Glide
30 | import com.firebase.ui.firestore.FirestoreRecyclerAdapter
31 | import com.firebase.ui.firestore.FirestoreRecyclerOptions
32 | import com.google.firebase.firestore.FirebaseFirestore
33 | import com.google.firebase.firestore.Query
34 | import com.google.firebase.storage.FirebaseStorage
35 | import com.hyperaware.doorbell.app.R
36 | import com.hyperaware.doorbell.app.model.Ring
37 | import java.text.DateFormat
38 |
39 | class ListRingsActivity : AppCompatActivity() {
40 |
41 | companion object {
42 | private val FIR_STORAGE = FirebaseStorage.getInstance()
43 | }
44 |
45 | override fun onCreate(savedInstanceState: Bundle?) {
46 | super.onCreate(savedInstanceState)
47 |
48 | setContentView(R.layout.activity_list_rings)
49 | val toolbar = findViewById(R.id.toolbar)
50 | setSupportActionBar(toolbar)
51 |
52 | val ringRecyclerView = findViewById(R.id.ringRecyclerView)
53 | ringRecyclerView.layoutManager = LinearLayoutManager(this)
54 | ringRecyclerView.adapter = mAdapter
55 | }
56 |
57 | public override fun onStart() {
58 | super.onStart()
59 | mAdapter.startListening()
60 | }
61 |
62 | public override fun onStop() {
63 | mAdapter.stopListening()
64 | super.onStop()
65 | }
66 |
67 |
68 | private inner class RingHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
69 | val dateTextView: TextView = itemView.findViewById(R.id.dateTextView)
70 | val ringerImageView: ImageView = itemView.findViewById(R.id.iv_guest)
71 | val answerImageView: ImageView = itemView.findViewById(R.id.iv_disposition)
72 | }
73 |
74 | private val query = FirebaseFirestore.getInstance()
75 | .collection("rings").orderBy("date", Query.Direction.DESCENDING)
76 | private val options = FirestoreRecyclerOptions.Builder()
77 | .setQuery(query, Ring::class.java)
78 | .build()
79 |
80 | private val mAdapter = object : FirestoreRecyclerAdapter(options) {
81 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RingHolder {
82 | val view = LayoutInflater.from(parent.context)
83 | .inflate(R.layout.ring_item, parent, false)
84 | return RingHolder(view)
85 | }
86 |
87 | override fun onBindViewHolder(holder: RingHolder, position: Int, ring: Ring) {
88 | val imageRef = FIR_STORAGE.getReference(ring.imagePath!!)
89 | val date = ring.date
90 | val dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG)
91 | holder.dateTextView.text = dateFormat.format(date)
92 | Glide.with(this@ListRingsActivity).load(imageRef).into(holder.ringerImageView)
93 | val answer = ring.answer
94 | if (answer != null && answer.disposition!!) {
95 | holder.answerImageView.setImageDrawable(resources.getDrawable(R.drawable.ic_check_black_24dp))
96 | }
97 | else {
98 | holder.answerImageView.setImageDrawable(resources.getDrawable(R.drawable.ic_do_not_disturb_black_24dp))
99 | }
100 | }
101 | }
102 |
103 | }
104 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hyperaware/doorbell/app/activity/MainActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.hyperaware.doorbell.app.activity
18 |
19 | import android.app.Activity
20 | import android.content.Intent
21 | import android.os.Bundle
22 | import android.support.design.widget.Snackbar
23 | import android.support.v7.app.AppCompatActivity
24 | import android.util.Log
25 | import android.view.View
26 | import android.widget.Button
27 | import com.firebase.ui.auth.AuthUI
28 | import com.firebase.ui.auth.IdpResponse
29 | import com.google.firebase.auth.FirebaseAuth
30 | import com.google.firebase.auth.FirebaseUser
31 | import com.hyperaware.doorbell.app.R
32 |
33 | class MainActivity : AppCompatActivity() {
34 |
35 | companion object {
36 | private const val TAG = "MainActivity"
37 | private const val RC_SIGN_IN = 1
38 | }
39 |
40 | private val auth = FirebaseAuth.getInstance()
41 | private var user: FirebaseUser? = null
42 |
43 | private lateinit var rootView : View
44 | private lateinit var vSignIn: Button
45 | private lateinit var vSignOut: Button
46 | private lateinit var vAuthConns: Button
47 | private lateinit var vAuthMessaging: Button
48 | private lateinit var vRings: Button
49 |
50 | override fun onCreate(savedInstanceState: Bundle?) {
51 | super.onCreate(savedInstanceState)
52 | setContentView(R.layout.activity_main)
53 |
54 | rootView = findViewById(R.id.root)
55 |
56 | vSignIn = findViewById(R.id.btn_sign_in)
57 | vSignIn.setOnClickListener {
58 | startActivityForResult(
59 | AuthUI.getInstance()
60 | .createSignInIntentBuilder()
61 | .setAvailableProviders(listOf(AuthUI.IdpConfig.GoogleBuilder().build()))
62 | .build(),
63 | RC_SIGN_IN)
64 | }
65 |
66 | vSignOut = findViewById(R.id.btn_sign_out)
67 | vSignOut.setOnClickListener {
68 | AuthUI.getInstance().signOut(this)
69 | .addOnSuccessListener(this) { Log.d(TAG, "Signed out") }
70 | .addOnFailureListener(this) { e -> Log.d(TAG, "Error signing out", e) }
71 | }
72 |
73 | vAuthConns = findViewById(R.id.btn_nearby_conns)
74 | vAuthConns.setOnClickListener {
75 | startActivity(Intent(this, NearbyConnectionsActivity::class.java))
76 | }
77 |
78 | vAuthMessaging = findViewById(R.id.btn_nearby_messaging)
79 | vAuthMessaging.setOnClickListener {
80 | startActivity(Intent(this, NearbyMessagingActivity::class.java))
81 | }
82 |
83 | vRings = findViewById(R.id.btn_rings)
84 | vRings.setOnClickListener {
85 | startActivity(Intent(this, ListRingsActivity::class.java))
86 | }
87 | }
88 |
89 | override fun onStart() {
90 | super.onStart()
91 | auth.addAuthStateListener(authStateListener)
92 | }
93 |
94 | override fun onStop() {
95 | auth.removeAuthStateListener(authStateListener)
96 | super.onStop()
97 | }
98 |
99 | override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
100 | super.onActivityResult(requestCode, resultCode, data)
101 | if (requestCode == RC_SIGN_IN) {
102 | val response = IdpResponse.fromResultIntent(data)
103 | if (resultCode == Activity.RESULT_OK) {
104 | Snackbar.make(rootView, "Signed in", Snackbar.LENGTH_SHORT).show()
105 | if (response != null) {
106 | Log.d(TAG, "idpToken ${response.idpToken}")
107 | }
108 | }
109 | else {
110 | Snackbar.make(rootView, "Not signed in", Snackbar.LENGTH_SHORT).show()
111 | if (response != null) {
112 | Log.e(TAG, "Sign in error ${response.error}")
113 | }
114 | }
115 | }
116 | }
117 |
118 | private val authStateListener = FirebaseAuth.AuthStateListener {
119 | user = auth.currentUser
120 | updateUi()
121 | }
122 |
123 | private fun updateUi() {
124 | vSignIn.isEnabled = user == null
125 | vSignOut.isEnabled = user != null
126 | vAuthConns.isEnabled = user != null
127 | vAuthMessaging.isEnabled = user != null
128 | vSignOut.isEnabled = user != null
129 | vRings.isEnabled = user != null
130 | }
131 |
132 | }
133 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hyperaware/doorbell/app/activity/NearbyConnectionsActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.hyperaware.doorbell.app.activity
18 |
19 | import android.Manifest
20 | import android.content.pm.PackageManager
21 | import android.os.Bundle
22 | import android.support.v4.app.ActivityCompat
23 | import android.support.v4.content.ContextCompat
24 | import android.support.v7.app.AppCompatActivity
25 | import android.util.Log
26 | import com.google.android.gms.auth.api.signin.GoogleSignIn
27 | import com.google.android.gms.nearby.Nearby
28 | import com.google.android.gms.nearby.connection.*
29 | import com.google.firebase.auth.FirebaseAuth
30 |
31 | class NearbyConnectionsActivity : AppCompatActivity() {
32 |
33 | companion object {
34 | private const val MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 0
35 | private const val TAG = "NearbyConnsActivity"
36 | }
37 |
38 | private val firebaseAuth = FirebaseAuth.getInstance()
39 | private lateinit var connectionsClient: ConnectionsClient
40 | private var connectedEndpointId: String? = null
41 |
42 | override fun onCreate(savedInstanceState: Bundle?) {
43 | super.onCreate(savedInstanceState)
44 |
45 | if (firebaseAuth.currentUser == null) {
46 | throw Exception("You can't do that here")
47 | }
48 |
49 | // setContentView(R.layout.activity_main)
50 | connectionsClient = Nearby.getConnectionsClient(this)
51 | }
52 |
53 | override fun onStart() {
54 | super.onStart()
55 | checkPermissionsForDiscovery()
56 | }
57 |
58 | override fun onStop() {
59 | stopDiscovery()
60 | super.onStop()
61 | }
62 |
63 | override fun onDestroy() {
64 | if (connectedEndpointId != null) {
65 | connectionsClient.disconnectFromEndpoint(connectedEndpointId!!)
66 | connectedEndpointId = null
67 | }
68 | super.onDestroy()
69 | }
70 |
71 | private fun checkPermissionsForDiscovery() {
72 | val perm = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
73 | if (perm != PackageManager.PERMISSION_GRANTED) {
74 | ActivityCompat.requestPermissions(
75 | this,
76 | arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),
77 | MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION
78 | )
79 | }
80 | else {
81 | startDiscovery()
82 | }
83 | }
84 |
85 | override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) {
86 | if (grantResults.size == 1) {
87 | startDiscovery()
88 | }
89 | else {
90 | Log.e(TAG, "User didn't grant permission")
91 | finish()
92 | }
93 | }
94 |
95 | private fun startDiscovery() {
96 | connectionsClient.startDiscovery(
97 | "com.hyperaware.doorbell.thing",
98 | endpointDiscoveryCallback,
99 | DiscoveryOptions.Builder().setStrategy(Strategy.P2P_CLUSTER).build()
100 | )
101 | .addOnSuccessListener(this) {
102 | Log.d(TAG, "startDiscovery onSuccess")
103 | }
104 | .addOnFailureListener(this) { e ->
105 | Log.e(TAG, "startAdvertising onFailure", e)
106 | }
107 | }
108 |
109 | private fun stopDiscovery() {
110 | connectionsClient.stopDiscovery()
111 | }
112 |
113 | private val endpointDiscoveryCallback = object : EndpointDiscoveryCallback() {
114 | override fun onEndpointFound(endpointId: String, info: DiscoveredEndpointInfo) {
115 | Log.d(TAG, "onEndpointFound $endpointId name: ${info.endpointName} id: ${info.serviceId}")
116 | connect(endpointId)
117 | }
118 |
119 | override fun onEndpointLost(endpointId: String) {
120 | Log.d(TAG, "onEndpointLost $endpointId")
121 | }
122 | }
123 |
124 | private fun connect(endpointId: String) {
125 | connectionsClient.requestConnection(
126 | "",
127 | endpointId,
128 | connectionLifecycleCallback
129 | )
130 | .addOnSuccessListener(this@NearbyConnectionsActivity) {
131 | Log.d(TAG, "requestConnection onSuccess")
132 | }
133 | .addOnFailureListener(this@NearbyConnectionsActivity) { e ->
134 | Log.e(TAG, "requestConnection onFailure", e)
135 | }
136 | }
137 |
138 | private val connectionLifecycleCallback = object : ConnectionLifecycleCallback() {
139 | override fun onConnectionInitiated(endpointId: String, info: ConnectionInfo) {
140 | Log.d(TAG, "onConnectionInitiated $endpointId name: ${info.endpointName}")
141 | connectionsClient.acceptConnection(endpointId, payloadCallback)
142 | .addOnSuccessListener(this@NearbyConnectionsActivity) {
143 | Log.d(TAG, "acceptConnection onSuccess")
144 | }
145 | .addOnFailureListener(this@NearbyConnectionsActivity) { e ->
146 | Log.e(TAG, "acceptConnection onFailure", e)
147 | }
148 | }
149 |
150 | override fun onConnectionResult(endpointId: String, resolution: ConnectionResolution) {
151 | Log.d(TAG, "onConnectionResult $endpointId status: ${resolution.status}")
152 | connectedEndpointId = endpointId
153 | val token = GoogleSignIn.getLastSignedInAccount(this@NearbyConnectionsActivity)!!.idToken!!
154 | sendPayload(endpointId, token)
155 | }
156 |
157 | override fun onDisconnected(endpointId: String) {
158 | Log.d(TAG, "onDisconnected $endpointId")
159 | finish()
160 | }
161 | }
162 |
163 | private fun sendPayload(endpointId: String, token: String) {
164 | Log.d(TAG, "Sending id token $token")
165 | val payload = Payload.fromBytes(token.toByteArray())
166 | connectionsClient.sendPayload(endpointId, payload)
167 | .addOnSuccessListener(this) {
168 | Log.d(TAG, "sendPayload onSuccess")
169 | }
170 | .addOnFailureListener(this) { e ->
171 | Log.e(TAG, "sendPayload onFailure", e)
172 | }
173 | }
174 |
175 | private val payloadCallback = object : PayloadCallback() {
176 | override fun onPayloadReceived(endpointId: String, payload: Payload) {
177 | Log.d(TAG, "onPayloadReceived $endpointId payload: ${payload.id}")
178 | Log.d(TAG, String(payload.asBytes()!!))
179 | }
180 |
181 | override fun onPayloadTransferUpdate(endpointId: String, update: PayloadTransferUpdate) {
182 | Log.d(TAG, "onPayloadTransferUpdate $endpointId ${update.status}")
183 | if (update.status == PayloadTransferUpdate.Status.SUCCESS) {
184 | Log.d(TAG, "Disconnecting")
185 | connectionsClient.disconnectFromEndpoint(endpointId)
186 | finish()
187 | }
188 | }
189 | }
190 |
191 | }
192 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hyperaware/doorbell/app/activity/NearbyMessagingActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.hyperaware.doorbell.app.activity
18 |
19 | import android.os.Bundle
20 | import android.os.Handler
21 | import android.support.v7.app.AppCompatActivity
22 | import android.util.Log
23 | import android.widget.TextView
24 | import android.widget.Toast
25 | import com.google.android.gms.auth.api.signin.GoogleSignIn
26 | import com.google.android.gms.nearby.Nearby
27 | import com.google.android.gms.nearby.messages.*
28 | import com.hyperaware.doorbell.app.R
29 | import com.hyperaware.doorbell.app.activity.NearbyMessagingActivity.UiState.*
30 |
31 | class NearbyMessagingActivity : AppCompatActivity() {
32 |
33 | companion object {
34 | private const val TAG = "NearbyMessagingActivity"
35 | }
36 |
37 | private val handler = Handler()
38 |
39 | private lateinit var tvStatus: TextView
40 |
41 | private lateinit var client: MessagesClient
42 | private lateinit var message: Message
43 |
44 | override fun onCreate(savedInstanceState: Bundle?) {
45 | super.onCreate(savedInstanceState)
46 |
47 | setContentView(R.layout.activity_auth)
48 | tvStatus = findViewById(R.id.tvStatus)
49 | updateUi(WaitingForPermission)
50 |
51 | client = Nearby.getMessagesClient(this)
52 |
53 | val lastSignedInAccount = GoogleSignIn.getLastSignedInAccount(this)
54 | if (lastSignedInAccount != null) {
55 | message = Message(lastSignedInAccount.idToken!!.toByteArray())
56 | }
57 | else {
58 | Toast.makeText(this, "Not logged in", Toast.LENGTH_SHORT).show()
59 | finish()
60 | }
61 | }
62 |
63 | override fun onStart() {
64 | super.onStart()
65 |
66 | tvStatus = findViewById(R.id.tvStatus)
67 | updateUi(WaitingForPermission)
68 |
69 | client.registerStatusCallback(statusCallback)
70 | }
71 |
72 | override fun onStop() {
73 | client.unpublish(message)
74 | client.unregisterStatusCallback(statusCallback)
75 |
76 | super.onStop()
77 | }
78 |
79 | private enum class UiState {
80 | WaitingForPermission,
81 | Publishing,
82 | PublishExpired,
83 | PublicationFailure,
84 | }
85 |
86 | private fun updateUi(uiState: UiState, finishOnDelay: Boolean = false) {
87 | Log.d(TAG, "uiState: $uiState")
88 | val message = when (uiState) {
89 | WaitingForPermission -> "Waiting for permission..."
90 | Publishing -> "Publishing..."
91 | PublishExpired -> "Nearby Messaging publish expired."
92 | PublicationFailure -> "Publication failure"
93 | }
94 |
95 | tvStatus.text = message
96 | if (finishOnDelay) {
97 | handler.postDelayed({ finish() }, 2000)
98 | }
99 | }
100 |
101 | private val statusCallback = object: StatusCallback() {
102 | override fun onPermissionChanged(permissionGranted: Boolean) {
103 | Log.d(TAG, "onPermissionChanged $permissionGranted")
104 | updateUi(Publishing)
105 | publish()
106 | }
107 | }
108 |
109 | private fun publish() {
110 | val strategy = Strategy.Builder()
111 | .setDiscoveryMode(Strategy.DISCOVERY_MODE_BROADCAST)
112 | .setTtlSeconds(Strategy.TTL_SECONDS_MAX)
113 | .build()
114 |
115 | val publishOpts = PublishOptions.Builder()
116 | .setStrategy(strategy)
117 | .setCallback(object : PublishCallback() {
118 | override fun onExpired() {
119 | Log.d(TAG, "onExpired")
120 | updateUi(PublishExpired, true)
121 | }
122 | })
123 | .build()
124 |
125 | client.publish(message, publishOpts)
126 | .addOnSuccessListener(this) {
127 | Log.e(TAG, "publish success")
128 | }
129 | .addOnFailureListener(this) { e ->
130 | Log.e(TAG, "publish failed", e)
131 | updateUi(PublicationFailure, true)
132 | }
133 | }
134 |
135 | }
136 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hyperaware/doorbell/app/fcm/MyInstanceIdService.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.hyperaware.doorbell.app.fcm
18 |
19 | import android.util.Log
20 |
21 | import com.google.firebase.iid.FirebaseInstanceId
22 | import com.google.firebase.iid.FirebaseInstanceIdService
23 | import com.google.firebase.messaging.FirebaseMessaging
24 |
25 | class MyInstanceIdService : FirebaseInstanceIdService() {
26 |
27 | companion object {
28 | private const val TAG = "MyInstanceIdService"
29 | }
30 |
31 | override fun onTokenRefresh() {
32 | super.onTokenRefresh()
33 | Log.d(TAG, "FCM token refresh: ${FirebaseInstanceId.getInstance().token!!}")
34 | FirebaseMessaging.getInstance().subscribeToTopic("rings")
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hyperaware/doorbell/app/fcm/OnRingMessagingService.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.hyperaware.doorbell.app.fcm
18 |
19 | import android.content.Intent
20 | import android.util.Log
21 |
22 | import com.google.firebase.messaging.FirebaseMessagingService
23 | import com.google.firebase.messaging.RemoteMessage
24 | import com.hyperaware.doorbell.app.activity.AnswerRingActivity
25 |
26 | class OnRingMessagingService : FirebaseMessagingService() {
27 |
28 | companion object {
29 | private const val TAG = "RingMessagingService"
30 | private const val PROP_RING_ID = "ring_id"
31 | }
32 |
33 | override fun onMessageReceived(remoteMessage: RemoteMessage) {
34 | super.onMessageReceived(remoteMessage)
35 | Log.d(TAG, "Ring message received")
36 |
37 | //
38 | // The incoming message should contain the ID of the ring
39 | //
40 |
41 | if (remoteMessage.data.containsKey(PROP_RING_ID)) {
42 | val ringId = remoteMessage.data[PROP_RING_ID]
43 | Log.d(TAG, "$PROP_RING_ID: $ringId")
44 | val intent = Intent(this, AnswerRingActivity::class.java)
45 | intent.putExtra(AnswerRingActivity.EXTRA_RING_ID, ringId)
46 | startActivity(intent)
47 | }
48 | else {
49 | Log.w(TAG, "Data message received without $PROP_RING_ID")
50 | }
51 | }
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hyperaware/doorbell/app/glide/FirebaseStorageGlideModule.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.hyperaware.doorbell.app.glide
18 |
19 | import android.content.Context
20 | import com.firebase.ui.storage.images.FirebaseImageLoader
21 | import com.bumptech.glide.Glide
22 | import com.bumptech.glide.Registry
23 | import com.bumptech.glide.annotation.GlideModule
24 | import com.bumptech.glide.module.AppGlideModule
25 | import com.google.firebase.storage.StorageReference
26 | import java.io.InputStream
27 |
28 | @GlideModule
29 | class MyAppGlideModule : AppGlideModule() {
30 |
31 | override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
32 | // Register FirebaseImageLoader to handle StorageReference
33 | registry.append(StorageReference::class.java, InputStream::class.java,
34 | FirebaseImageLoader.Factory())
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hyperaware/doorbell/app/model/Ring.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.hyperaware.doorbell.app.model
18 |
19 | import java.util.*
20 |
21 | class Ring {
22 |
23 | var id: String? = null
24 | var date: Date? = null
25 | var imagePath: String? = null
26 | var answer: RingAnswer? = null
27 |
28 | }
29 |
30 | class RingAnswer {
31 |
32 | var uid: String? = null
33 | var disposition: Boolean? = null
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-hdpi/ic_check_black_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingDoug/firebase-doorbell/bb5992405741e779d09494c6b88073d7179f7238/app/src/main/res/drawable-hdpi/ic_check_black_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-hdpi/ic_do_not_disturb_black_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingDoug/firebase-doorbell/bb5992405741e779d09494c6b88073d7179f7238/app/src/main/res/drawable-hdpi/ic_do_not_disturb_black_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-hdpi/ic_face_black_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingDoug/firebase-doorbell/bb5992405741e779d09494c6b88073d7179f7238/app/src/main/res/drawable-hdpi/ic_face_black_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-mdpi/ic_check_black_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingDoug/firebase-doorbell/bb5992405741e779d09494c6b88073d7179f7238/app/src/main/res/drawable-mdpi/ic_check_black_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-mdpi/ic_do_not_disturb_black_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingDoug/firebase-doorbell/bb5992405741e779d09494c6b88073d7179f7238/app/src/main/res/drawable-mdpi/ic_do_not_disturb_black_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-mdpi/ic_face_black_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingDoug/firebase-doorbell/bb5992405741e779d09494c6b88073d7179f7238/app/src/main/res/drawable-mdpi/ic_face_black_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xhdpi/ic_check_black_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingDoug/firebase-doorbell/bb5992405741e779d09494c6b88073d7179f7238/app/src/main/res/drawable-xhdpi/ic_check_black_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xhdpi/ic_do_not_disturb_black_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingDoug/firebase-doorbell/bb5992405741e779d09494c6b88073d7179f7238/app/src/main/res/drawable-xhdpi/ic_do_not_disturb_black_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xhdpi/ic_face_black_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingDoug/firebase-doorbell/bb5992405741e779d09494c6b88073d7179f7238/app/src/main/res/drawable-xhdpi/ic_face_black_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/ic_check_black_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingDoug/firebase-doorbell/bb5992405741e779d09494c6b88073d7179f7238/app/src/main/res/drawable-xxhdpi/ic_check_black_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/ic_do_not_disturb_black_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingDoug/firebase-doorbell/bb5992405741e779d09494c6b88073d7179f7238/app/src/main/res/drawable-xxhdpi/ic_do_not_disturb_black_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/ic_face_black_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingDoug/firebase-doorbell/bb5992405741e779d09494c6b88073d7179f7238/app/src/main/res/drawable-xxhdpi/ic_face_black_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxxhdpi/ic_check_black_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingDoug/firebase-doorbell/bb5992405741e779d09494c6b88073d7179f7238/app/src/main/res/drawable-xxxhdpi/ic_check_black_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxxhdpi/ic_do_not_disturb_black_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingDoug/firebase-doorbell/bb5992405741e779d09494c6b88073d7179f7238/app/src/main/res/drawable-xxxhdpi/ic_do_not_disturb_black_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxxhdpi/ic_face_black_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingDoug/firebase-doorbell/bb5992405741e779d09494c6b88073d7179f7238/app/src/main/res/drawable-xxxhdpi/ic_face_black_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_answer.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
23 |
24 |
37 |
38 |
49 |
50 |
60 |
61 |
69 |
70 |
71 |
72 |
73 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_auth.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_list_rings.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
17 |
18 |
25 |
26 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
19 |
20 |
26 |
27 |
33 |
34 |
40 |
41 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/content_list_rings.xml:
--------------------------------------------------------------------------------
1 |
2 |
11 |
12 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/ring_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
18 |
19 |
35 |
36 |
49 |
50 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingDoug/firebase-doorbell/bb5992405741e779d09494c6b88073d7179f7238/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingDoug/firebase-doorbell/bb5992405741e779d09494c6b88073d7179f7238/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingDoug/firebase-doorbell/bb5992405741e779d09494c6b88073d7179f7238/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingDoug/firebase-doorbell/bb5992405741e779d09494c6b88073d7179f7238/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingDoug/firebase-doorbell/bb5992405741e779d09494c6b88073d7179f7238/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingDoug/firebase-doorbell/bb5992405741e779d09494c6b88073d7179f7238/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingDoug/firebase-doorbell/bb5992405741e779d09494c6b88073d7179f7238/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingDoug/firebase-doorbell/bb5992405741e779d09494c6b88073d7179f7238/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingDoug/firebase-doorbell/bb5992405741e779d09494c6b88073d7179f7238/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingDoug/firebase-doorbell/bb5992405741e779d09494c6b88073d7179f7238/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 180dp
3 | 16dp
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | Firebase Doorbell
4 | Settings
5 |
6 | Let them in?
7 | Yes
8 | No
9 |
10 | Guest image
11 | Disposition
12 |
13 | Answering a ring requires that you log into this app.
14 |
15 |
16 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/backend/.firebaserc:
--------------------------------------------------------------------------------
1 | {
2 | "projects": {
3 | "default": "fir-doorbell-dev"
4 | }
5 | }
6 |
--------------------------------------------------------------------------------
/backend/.gitignore:
--------------------------------------------------------------------------------
1 | service-account.json
2 |
--------------------------------------------------------------------------------
/backend/firebase.json:
--------------------------------------------------------------------------------
1 | {
2 | "storage": {
3 | "rules": "storage.rules"
4 | },
5 | "firestore": {
6 | "rules": "firestore.rules",
7 | "indexes": "firestore.indexes.json"
8 | },
9 | "functions": {
10 | "predeploy": [
11 | "npm --prefix $RESOURCE_DIR run lint",
12 | "npm --prefix $RESOURCE_DIR run build"
13 | ]
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/backend/firestore.indexes.json:
--------------------------------------------------------------------------------
1 | {
2 | "indexes": []
3 | }
4 |
--------------------------------------------------------------------------------
/backend/firestore.rules:
--------------------------------------------------------------------------------
1 | service cloud.firestore {
2 | match /databases/{database}/documents {
3 | match /{document=**} {
4 | allow read, write: if request.auth != null;
5 | }
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/backend/functions/.gitignore:
--------------------------------------------------------------------------------
1 | /node_modules
2 | /lib
3 | .runtimeconfig.json
4 |
--------------------------------------------------------------------------------
/backend/functions/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "functions",
3 | "scripts": {
4 | "lint": "tslint --project tsconfig.json",
5 | "build": "tsc",
6 | "serve": "npm run build && firebase serve --only functions",
7 | "shell": "npm run build && firebase experimental:functions:shell",
8 | "start": "npm run shell",
9 | "deploy": "firebase deploy --only functions",
10 | "logs": "firebase functions:log"
11 | },
12 | "main": "lib/index.js",
13 | "dependencies": {
14 | "firebase-admin": "^6.0.0",
15 | "firebase-functions": "^2.0.5",
16 | "source-map-support": "^0.5.9"
17 | },
18 | "devDependencies": {
19 | "tslint": "^5.11.0",
20 | "typescript": "^3.1.2"
21 | },
22 | "private": true
23 | }
24 |
--------------------------------------------------------------------------------
/backend/functions/src/index.ts:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | const sourceMapSupport = require('source-map-support')
18 | sourceMapSupport.install()
19 |
20 | import * as functions from 'firebase-functions'
21 | import * as admin from 'firebase-admin'
22 | import { basename } from 'path'
23 | import { DocumentSnapshot } from 'firebase-functions/lib/providers/firestore';
24 |
25 | type Ring = {
26 | id: string,
27 | date: Date,
28 | imagePath: string,
29 | answer?: RingAnswer
30 | }
31 |
32 | type RingAnswer = {
33 | uid: string
34 | disposition: boolean
35 | }
36 |
37 | const cert = JSON.parse(functions.config().serviceaccount.cert.replace(new RegExp("'", 'g'), ''))
38 | const adminConfig = JSON.parse(process.env.FIREBASE_CONFIG)
39 | adminConfig.credential = admin.credential.cert(cert)
40 | admin.initializeApp(adminConfig)
41 |
42 | const firestore = admin.firestore()
43 | const fcm = admin.messaging()
44 |
45 | export const onRing = functions.storage.object().onFinalize(_onRing)
46 | async function _onRing(object: functions.storage.ObjectMetadata): Promise {
47 | console.log(object)
48 |
49 | const path = object.name
50 | const id = basename(path, '.jpg')
51 |
52 | try {
53 | // Add a document to Firestore with the details of this ring
54 | //
55 | const ring: Ring = {
56 | id: id,
57 | date: new Date(),
58 | imagePath: path,
59 | }
60 | console.log('Ring:', ring)
61 | await firestore.collection('rings').doc(id).set(ring)
62 |
63 | // Send a notification to the app
64 | //
65 | const payload = {
66 | notification: {
67 | title: 'Ring Ring!',
68 | body: 'There is someone at the door!',
69 | click_action: 'com.hyperaware.doorbell.ANSWER_RING'
70 | },
71 | data: {
72 | ring_id: id
73 | }
74 | }
75 |
76 | console.log('Sending FCM payload to topic "rings"', payload)
77 | const response = await fcm.sendToTopic('rings', payload)
78 | console.log('ring sent:', response)
79 | }
80 | catch (err) {
81 | console.error('ring not sent:', err)
82 | }
83 | }
84 |
85 |
86 | export const onAnswer = functions.firestore.document('/rings/{ringId}').onUpdate(_onAnswer)
87 | async function _onAnswer(change: functions.Change): Promise {
88 | const ringId = change.before.id // e.g. 20180327123000
89 | const previous = change.before.data() as Ring
90 | const ring = change.after.data() as Ring
91 | console.log(`Ring`, ring)
92 |
93 | // Only interested in rings that have a new answer
94 | if (previous.answer || !ring.answer) {
95 | console.log("This is not the update you're looking for.")
96 | return Promise.resolve()
97 | }
98 |
99 | const payload = {
100 | data: {
101 | disposition: ring.answer.disposition.toString(),
102 | ring_id: ringId
103 | }
104 | }
105 | try {
106 | const response = await fcm.sendToTopic('answers', payload)
107 | console.log(`ring ${ringId} answer sent:`, response)
108 | }
109 | catch (err) {
110 | console.error(`ring ${ringId} answer error:`, err)
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/backend/functions/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "lib": ["es6"],
4 | "module": "commonjs",
5 | "noImplicitReturns": true,
6 | "outDir": "lib",
7 | "sourceMap": true,
8 | "target": "es6"
9 | },
10 | "compileOnSave": true,
11 | "include": [
12 | "src"
13 | ]
14 | }
15 |
--------------------------------------------------------------------------------
/backend/functions/tslint.json:
--------------------------------------------------------------------------------
1 | {
2 | "rules": {
3 | // -- Strict errors --
4 | // These lint rules are likely always a good idea.
5 |
6 | // Force function overloads to be declared together. This ensures readers understand APIs.
7 | "adjacent-overload-signatures": true,
8 |
9 | // Do not allow the subtle/obscure comma operator.
10 | "ban-comma-operator": true,
11 |
12 | // Do not allow internal modules or namespaces . These are deprecated in favor of ES6 modules.
13 | "no-namespace": true,
14 |
15 | // Do not allow parameters to be reassigned. To avoid bugs, developers should instead assign new values to new vars.
16 | "no-parameter-reassignment": true,
17 |
18 | // Force the use of ES6-style imports instead of /// imports.
19 | "no-reference": true,
20 |
21 | // Do not allow type assertions that do nothing. This is a big warning that the developer may not understand the
22 | // code currently being edited (they may be incorrectly handling a different type case that does not exist).
23 | "no-unnecessary-type-assertion": true,
24 |
25 | // Disallow nonsensical label usage.
26 | "label-position": true,
27 |
28 | // Disallows the (often typo) syntax if (var1 = var2). Replace with if (var2) { var1 = var2 }.
29 | "no-conditional-assignment": true,
30 |
31 | // Disallows constructors for primitive types (e.g. new Number('123'), though Number('123') is still allowed).
32 | "no-construct": true,
33 |
34 | // Do not allow super() to be called twice in a constructor.
35 | "no-duplicate-super": true,
36 |
37 | // Do not allow the same case to appear more than once in a switch block.
38 | "no-duplicate-switch-case": true,
39 |
40 | // Do not allow a variable to be declared more than once in the same block. Consider function parameters in this
41 | // rule.
42 | "no-duplicate-variable": [true, "check-parameters"],
43 |
44 | // Disallows a variable definition in an inner scope from shadowing a variable in an outer scope. Developers should
45 | // instead use a separate variable name.
46 | "no-shadowed-variable": true,
47 |
48 | // Empty blocks are almost never needed. Allow the one general exception: empty catch blocks.
49 | "no-empty": [true, "allow-empty-catch"],
50 |
51 | // Functions must either be handled directly (e.g. with a catch() handler) or returned to another function.
52 | // This is a major source of errors in Cloud Functions and the team strongly recommends leaving this rule on.
53 | "no-floating-promises": true,
54 |
55 | // Do not allow any imports for modules that are not in package.json. These will almost certainly fail when
56 | // deployed.
57 | "no-implicit-dependencies": true,
58 |
59 | // The 'this' keyword can only be used inside of classes.
60 | "no-invalid-this": true,
61 |
62 | // Do not allow strings to be thrown because they will not include stack traces. Throw Errors instead.
63 | "no-string-throw": true,
64 |
65 | // Disallow control flow statements, such as return, continue, break, and throw in finally blocks.
66 | "no-unsafe-finally": true,
67 |
68 | // Do not allow variables to be used before they are declared.
69 | "no-use-before-declare": true,
70 |
71 | // Expressions must always return a value. Avoids common errors like const myValue = functionReturningVoid();
72 | "no-void-expression": [true, "ignore-arrow-function-shorthand"],
73 |
74 | // Disallow duplicate imports in the same file.
75 | "no-duplicate-imports": true,
76 |
77 |
78 | // -- Strong Warnings --
79 | // These rules should almost never be needed, but may be included due to legacy code.
80 | // They are left as a warning to avoid frustration with blocked deploys when the developer
81 | // understand the warning and wants to deploy anyway.
82 |
83 | // Warn when an empty interface is defined. These are generally not useful.
84 | "no-empty-interface": {"severity": "warning"},
85 |
86 | // Warn when an import will have side effects.
87 | "no-import-side-effect": {"severity": "warning"},
88 |
89 | // Warn when variables are defined with var. Var has subtle meaning that can lead to bugs. Strongly prefer const for
90 | // most values and let for values that will change.
91 | "no-var-keyword": {"severity": "warning"},
92 |
93 | // Prefer === and !== over == and !=. The latter operators support overloads that are often accidental.
94 | "triple-equals": {"severity": "warning"},
95 |
96 | // Warn when using deprecated APIs.
97 | "deprecation": {"severity": "warning"},
98 |
99 | // -- Light Warnigns --
100 | // These rules are intended to help developers use better style. Simpler code has fewer bugs. These would be "info"
101 | // if TSLint supported such a level.
102 |
103 | // prefer for( ... of ... ) to an index loop when the index is only used to fetch an object from an array.
104 | // (Even better: check out utils like .map if transforming an array!)
105 | "prefer-for-of": {"severity": "warning"},
106 |
107 | // Warns if function overloads could be unified into a single function with optional or rest parameters.
108 | "unified-signatures": {"severity": "warning"},
109 |
110 | // Warns if code has an import or variable that is unused.
111 | "no-unused-variable": {"severity": "warning"},
112 |
113 | // Prefer const for values that will not change. This better documents code.
114 | "prefer-const": {"severity": "warning"},
115 |
116 | // Multi-line object liiterals and function calls should have a trailing comma. This helps avoid merge conflicts.
117 | "trailing-comma": {"severity": "warning"}
118 | },
119 |
120 | "defaultSeverity": "error"
121 | }
122 |
--------------------------------------------------------------------------------
/backend/scripts/config-env.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | #
3 | # Copyright 2018 Google LLC
4 | #
5 | # Licensed under the Apache License, Version 2.0 (the "License");
6 | # you may not use this file except in compliance with the License.
7 | # You may obtain a copy of the License at
8 | #
9 | # https://www.apache.org/licenses/LICENSE-2.0
10 | #
11 | # Unless required by applicable law or agreed to in writing, software
12 | # distributed under the License is distributed on an "AS IS" BASIS,
13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | # See the License for the specific language governing permissions and
15 | # limitations under the License.
16 | #
17 |
18 | cert=`cat "$1"`
19 | firebase functions:config:set "serviceaccount.cert='$cert'"
20 |
--------------------------------------------------------------------------------
/backend/storage.rules:
--------------------------------------------------------------------------------
1 | service firebase.storage {
2 | match /b/{bucket}/o {
3 | match /{allPaths=**} {
4 | allow read, write: if request.auth != null;
5 | }
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | ext {
3 | kotlin_version = '1.2.71'
4 | android_support_version = '27.1.1'
5 | thing_play_services_version = '12.0.1'
6 | app_play_services_version = '12.0.1'
7 | firebase_ui_version = '3.3.0'
8 | glide_version = '4.7.1'
9 | }
10 | repositories {
11 | google()
12 | jcenter()
13 | maven { url 'https://maven.fabric.io/public' }
14 | }
15 | dependencies {
16 | classpath 'com.android.tools.build:gradle:3.2.1'
17 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
18 | classpath 'com.google.gms:google-services:4.1.0'
19 | classpath 'com.google.firebase:firebase-plugins:1.1.5'
20 | classpath 'io.fabric.tools:gradle:1.25.4'
21 | }
22 | }
23 |
24 | allprojects {
25 | repositories {
26 | google()
27 | jcenter()
28 | }
29 | }
30 |
31 | task clean(type: Delete) {
32 | delete rootProject.buildDir
33 | }
34 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingDoug/firebase-doorbell/bb5992405741e779d09494c6b88073d7179f7238/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | zipStoreBase=GRADLE_USER_HOME
4 | zipStorePath=wrapper/dists
5 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.2-all.zip
6 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 | include ':thing'
3 |
--------------------------------------------------------------------------------
/thing/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-android-extensions'
4 | apply plugin: 'io.fabric'
5 |
6 | android {
7 | compileSdkVersion 27
8 | defaultConfig {
9 | applicationId "com.hyperaware.doorbell.thing"
10 | minSdkVersion 27
11 | targetSdkVersion 27
12 | versionCode 1
13 | versionName "1.0"
14 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
15 | }
16 | buildTypes {
17 | release {
18 | minifyEnabled false
19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
20 | }
21 | }
22 |
23 | flavorDimensions "fake"
24 | productFlavors {
25 | realThing {
26 | dimension "fake"
27 | }
28 | fakeThing {
29 | dimension "fake"
30 | }
31 | }
32 | }
33 |
34 | dependencies {
35 | compileOnly 'com.google.android.things:androidthings:1.0'
36 |
37 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
38 |
39 | implementation "com.android.support:support-v13:$android_support_version"
40 | implementation "com.android.support:appcompat-v7:$android_support_version"
41 | implementation 'com.android.support.constraint:constraint-layout:1.1.0'
42 |
43 | realThingImplementation 'com.google.android.things.contrib:driver-rainbowhat:0.10'
44 |
45 | implementation "com.google.android.gms:play-services-base:$thing_play_services_version"
46 | implementation "com.google.android.gms:play-services-nearby:$thing_play_services_version"
47 | implementation "com.google.firebase:firebase-core:$thing_play_services_version"
48 | implementation "com.google.firebase:firebase-auth:$thing_play_services_version"
49 | implementation "com.google.firebase:firebase-storage:$thing_play_services_version"
50 | implementation "com.google.firebase:firebase-messaging:$thing_play_services_version"
51 | implementation "com.crashlytics.sdk.android:crashlytics:2.9.3"
52 | }
53 |
54 | apply plugin: 'com.google.gms.google-services'
55 |
--------------------------------------------------------------------------------
/thing/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/thing/src/fakeThing/java/com/hyperaware/doorbell/thing/activity/MainActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.hyperaware.doorbell.thing.activity
18 |
19 | class MainActivity : BaseMainActivity()
20 |
--------------------------------------------------------------------------------
/thing/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
19 |
20 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
47 |
48 |
49 |
50 |
51 |
52 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
--------------------------------------------------------------------------------
/thing/src/main/java/com/hyperaware/doorbell/thing/activity/AutoFitSurfaceView.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.hyperaware.doorbell.thing.activity
18 |
19 | import android.content.Context
20 | import android.util.AttributeSet
21 | import android.util.Log
22 | import android.view.SurfaceView
23 | import android.view.TextureView
24 | import android.view.View
25 |
26 | /**
27 | * A [TextureView] that can be adjusted to a specified aspect ratio.
28 | */
29 | class AutoFitSurfaceView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : SurfaceView(context, attrs, defStyle) {
30 |
31 | private var mRatioWidth = 0
32 | private var mRatioHeight = 0
33 |
34 | /**
35 | * Sets the aspect ratio for this view. The size of the view will be measured based on the ratio
36 | * calculated from the parameters. Note that the actual sizes of parameters don't matter, that
37 | * is, calling setAspectRatio(2, 3) and setAspectRatio(4, 6) make the same result.
38 | *
39 | * @param width Relative horizontal size
40 | * @param height Relative vertical size
41 | */
42 | fun setAspectRatio(width: Int, height: Int) {
43 | if (width < 0 || height < 0) {
44 | throw IllegalArgumentException("Size cannot be negative.")
45 | }
46 | mRatioWidth = width
47 | mRatioHeight = height
48 | requestLayout()
49 | }
50 |
51 | override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
52 | super.onMeasure(widthMeasureSpec, heightMeasureSpec)
53 | val width = View.MeasureSpec.getSize(widthMeasureSpec)
54 | val height = View.MeasureSpec.getSize(heightMeasureSpec)
55 | val measuredWidth: Int
56 | val measuredHeight: Int
57 | if (0 == mRatioWidth || 0 == mRatioHeight) {
58 | measuredWidth = width
59 | measuredHeight = height
60 | }
61 | else {
62 | if (width < height * mRatioWidth / mRatioHeight) {
63 | measuredWidth = width
64 | measuredHeight = width * mRatioHeight / mRatioWidth
65 | }
66 | else {
67 | measuredWidth = height * mRatioWidth / mRatioHeight
68 | measuredHeight = height
69 | }
70 | }
71 | setMeasuredDimension(measuredWidth, measuredHeight)
72 | Log.d("AutoFitSurfaceView", "width=$measuredWidth height=$measuredHeight")
73 | }
74 |
75 | }
76 |
--------------------------------------------------------------------------------
/thing/src/main/java/com/hyperaware/doorbell/thing/activity/BaseMainActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.hyperaware.doorbell.thing.activity
18 |
19 | import android.app.Activity
20 | import android.content.Intent
21 | import android.net.Uri
22 | import android.os.Bundle
23 | import android.util.Log
24 | import android.widget.Button
25 | import com.google.firebase.storage.FirebaseStorage
26 | import com.hyperaware.doorbell.thing.R
27 | import java.io.File
28 | import java.text.SimpleDateFormat
29 | import java.util.*
30 |
31 | abstract class BaseMainActivity : Activity() {
32 |
33 | companion object {
34 | private const val TAG = "BaseMainActivity"
35 | private const val REQUEST_TAKE_PICTURE = 0
36 | }
37 |
38 | protected lateinit var buttonRing: Button
39 |
40 | override fun onCreate(savedInstanceState: Bundle?) {
41 | super.onCreate(savedInstanceState)
42 | Log.i(TAG, "Starting MainActivity")
43 | initViews()
44 | }
45 |
46 | private fun initViews() {
47 | setContentView(R.layout.main)
48 | buttonRing = findViewById(R.id.ring)
49 | buttonRing.setOnClickListener { onRingClick() }
50 | }
51 |
52 |
53 | override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
54 | when (resultCode) {
55 | Activity.RESULT_CANCELED -> {}
56 | Camera2Activity.RESULT_PICTURE -> {
57 | val file = data!!.getStringExtra(Camera2Activity.EXTRA_PICTURE_FILE)
58 | uploadFile(File(file))
59 | }
60 | }
61 | }
62 |
63 | private fun uploadFile(file: File) {
64 | val sdf = SimpleDateFormat("yyyyMMddHHmmss", Locale.US)
65 | val storagePath = "/pictures/${sdf.format(Date())}.jpg"
66 | Log.i(TAG, "Uploading to $file to $storagePath")
67 | val ref = FirebaseStorage.getInstance().getReference(storagePath)
68 | ref.putFile(Uri.fromFile(file))
69 | .addOnSuccessListener(this) {
70 | Log.i(TAG, "Picture uploaded")
71 | }
72 | .addOnFailureListener(this) { e ->
73 | Log.i(TAG, "Upload failed", e)
74 | }
75 | .addOnCompleteListener(this) {
76 | file.delete()
77 | }
78 | }
79 |
80 | protected fun onRingClick() {
81 | startActivityForResult(Intent(this, Camera2Activity::class.java), REQUEST_TAKE_PICTURE)
82 | }
83 |
84 | }
85 |
--------------------------------------------------------------------------------
/thing/src/main/java/com/hyperaware/doorbell/thing/activity/Camera2Activity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.hyperaware.doorbell.thing.activity
18 |
19 | import android.app.Activity
20 | import android.os.Bundle
21 | import com.hyperaware.doorbell.thing.R
22 |
23 | class Camera2Activity : Activity() {
24 |
25 | override fun onCreate(savedInstanceState: Bundle?) {
26 | super.onCreate(savedInstanceState)
27 | setContentView(R.layout.activity_camera)
28 | if (null == savedInstanceState) {
29 | fragmentManager.beginTransaction()
30 | .replace(R.id.container, Camera2BasicFragment.newInstance())
31 | .commit()
32 | }
33 | }
34 |
35 | companion object {
36 | const val RESULT_PICTURE = Activity.RESULT_FIRST_USER
37 | const val EXTRA_PICTURE_FILE = "picture_file"
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/thing/src/main/java/com/hyperaware/doorbell/thing/activity/Camera2BasicFragment.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.hyperaware.doorbell.thing.activity
18 |
19 | import android.Manifest
20 | import android.app.AlertDialog
21 | import android.app.Dialog
22 | import android.app.DialogFragment
23 | import android.app.Fragment
24 | import android.content.Context
25 | import android.content.Intent
26 | import android.content.pm.PackageManager
27 | import android.content.res.Configuration
28 | import android.graphics.ImageFormat
29 | import android.graphics.Point
30 | import android.hardware.camera2.*
31 | import android.hardware.camera2.CameraCaptureSession.CaptureCallback
32 | import android.hardware.camera2.params.StreamConfigurationMap
33 | import android.media.Image
34 | import android.media.ImageReader
35 | import android.os.Bundle
36 | import android.os.Handler
37 | import android.os.HandlerThread
38 | import android.support.v4.app.ActivityCompat
39 | import android.support.v4.content.ContextCompat
40 | import android.util.Log
41 | import android.util.Size
42 | import android.util.SparseIntArray
43 | import android.view.*
44 | import android.widget.TextView
45 | import android.widget.Toast
46 | import com.hyperaware.doorbell.thing.R
47 | import java.io.File
48 | import java.io.FileOutputStream
49 | import java.util.*
50 | import java.util.concurrent.Semaphore
51 | import java.util.concurrent.TimeUnit
52 |
53 | class Camera2BasicFragment : Fragment(), View.OnClickListener, ActivityCompat.OnRequestPermissionsResultCallback, CountdownTimer.Listener {
54 |
55 | /**
56 | * ID of the current [CameraDevice].
57 | */
58 | private lateinit var mCameraId: String
59 |
60 | /**
61 | * An [AutoFitSurfaceView] for camera preview.
62 | */
63 | private lateinit var mSurfaceView: AutoFitSurfaceView
64 | private lateinit var tvTimer: TextView
65 |
66 | /**
67 | * A [CameraCaptureSession] for camera preview.
68 | */
69 | private var mCaptureSession: CameraCaptureSession? = null
70 |
71 | /**
72 | * A reference to the opened [CameraDevice].
73 | */
74 | private var mCameraDevice: CameraDevice? = null
75 |
76 | /**
77 | * The [Size] of camera preview.
78 | */
79 | // private var mPreviewSize: Size? = null
80 |
81 | private val countdownTimer = CountdownTimer(5, this)
82 |
83 | /**
84 | * [CameraDevice.StateCallback] is called when [CameraDevice] changes its state.
85 | */
86 | private val mStateCallback = object : CameraDevice.StateCallback() {
87 |
88 | override fun onOpened(cameraDevice: CameraDevice) {
89 | // This method is called when the camera is opened. We start camera preview here.
90 | mCameraOpenCloseLock.release()
91 | mCameraDevice = cameraDevice
92 | createCameraPreviewSession()
93 | }
94 |
95 | override fun onDisconnected(cameraDevice: CameraDevice) {
96 | mCameraOpenCloseLock.release()
97 | cameraDevice.close()
98 | mCameraDevice = null
99 | }
100 |
101 | override fun onError(cameraDevice: CameraDevice, error: Int) {
102 | Log.e(TAG, "Camera error $error")
103 | mCameraOpenCloseLock.release()
104 | cameraDevice.close()
105 | mCameraDevice = null
106 | activity.finish()
107 | }
108 |
109 | }
110 |
111 | /**
112 | * An additional thread for running tasks that shouldn't block the UI.
113 | */
114 | private var mBackgroundThread: HandlerThread? = null
115 |
116 | /**
117 | * A [Handler] for running tasks in the background.
118 | */
119 | private var mBackgroundHandler: Handler? = null
120 |
121 | /**
122 | * An [ImageReader] that handles still image capture.
123 | */
124 | private var mImageReader: ImageReader? = null
125 |
126 | /**
127 | * This is the output file for our picture.
128 | */
129 | private lateinit var mFile: File
130 |
131 | /**
132 | * This a callback object for the [ImageReader]. "onImageAvailable" will be called when a
133 | * still image is ready to be saved.
134 | */
135 | private val mOnImageAvailableListener = ImageReader.OnImageAvailableListener { reader ->
136 | Log.d(TAG, "ImageReader.onImageAvailable")
137 | mBackgroundHandler!!.post(ImageSaver(reader.acquireNextImage(), mFile))
138 | }
139 |
140 | /**
141 | * [CaptureRequest.Builder] for the camera preview
142 | */
143 | private var mPreviewRequestBuilder: CaptureRequest.Builder? = null
144 |
145 | /**
146 | * [CaptureRequest] generated by [.mPreviewRequestBuilder]
147 | */
148 | private var mPreviewRequest: CaptureRequest? = null
149 |
150 | /**
151 | * The current state of camera state for taking pictures.
152 | *
153 | * @see .mCaptureCallback
154 | */
155 | private var mState = STATE_PREVIEW
156 |
157 | /**
158 | * A [Semaphore] to prevent the app from exiting before closing the camera.
159 | */
160 | private val mCameraOpenCloseLock = Semaphore(1)
161 |
162 | /**
163 | * Whether the current camera device supports Flash or not.
164 | */
165 | private var mFlashSupported: Boolean = false
166 |
167 | /**
168 | * Orientation of the camera sensor
169 | */
170 | private var mSensorOrientation: Int = 0
171 |
172 | /**
173 | * A [CaptureCallback] that handles events related to JPEG capture.
174 | */
175 | private val mCaptureCallback = object : CaptureCallback() {
176 |
177 | private fun process(result: CaptureResult) {
178 | when (mState) {
179 | // We have nothing to do when the camera preview is working normally.
180 | STATE_PREVIEW -> {}
181 | STATE_WAITING_LOCK -> {
182 | captureStillPicture()
183 | mState = STATE_PICTURE_TAKEN
184 | }
185 | STATE_WAITING_PRECAPTURE -> {
186 | // CONTROL_AE_STATE can be null on some devices
187 | val aeState = result.get(CaptureResult.CONTROL_AE_STATE)
188 | if (aeState == null ||
189 | aeState == CaptureResult.CONTROL_AE_STATE_PRECAPTURE ||
190 | aeState == CaptureRequest.CONTROL_AE_STATE_FLASH_REQUIRED) {
191 | mState = STATE_WAITING_NON_PRECAPTURE
192 | }
193 | }
194 | STATE_WAITING_NON_PRECAPTURE -> {
195 | // CONTROL_AE_STATE can be null on some devices
196 | val aeState = result.get(CaptureResult.CONTROL_AE_STATE)
197 | if (aeState == null || aeState != CaptureResult.CONTROL_AE_STATE_PRECAPTURE) {
198 | mState = STATE_PICTURE_TAKEN
199 | captureStillPicture()
200 | }
201 | }
202 | }
203 | }
204 |
205 | override fun onCaptureProgressed(session: CameraCaptureSession, request: CaptureRequest, partialResult: CaptureResult) {
206 | process(partialResult)
207 | }
208 |
209 | override fun onCaptureCompleted(session: CameraCaptureSession, request: CaptureRequest, result: TotalCaptureResult) {
210 | process(result)
211 | }
212 |
213 | }
214 |
215 | private val captureCallback = object : CaptureCallback() {
216 | override fun onCaptureCompleted(session: CameraCaptureSession, request: CaptureRequest, result: TotalCaptureResult) {
217 | Log.d(TAG, "Saved: " + mFile.toString())
218 | unlockFocus()
219 | val intent = Intent()
220 | intent.putExtra(Camera2Activity.EXTRA_PICTURE_FILE, mFile.toString())
221 | activity.setResult(Camera2Activity.RESULT_PICTURE, intent)
222 | activity.finish()
223 | }
224 | }
225 |
226 | /**
227 | * Shows a [Toast] on the UI thread.
228 | *
229 | * @param text The message to show
230 | */
231 | private fun showToast(text: String) {
232 | activity.runOnUiThread { Toast.makeText(activity, text, Toast.LENGTH_SHORT).show() }
233 | }
234 |
235 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
236 | savedInstanceState: Bundle?): View {
237 | return inflater.inflate(R.layout.fragment_camera2_basic, container, false)
238 | }
239 |
240 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
241 | view.findViewById(R.id.picture).setOnClickListener(this)
242 | view.findViewById(R.id.back).setOnClickListener(this)
243 | tvTimer = view.findViewById(R.id.timer)
244 | tvTimer.text = ""
245 | mSurfaceView = view.findViewById(R.id.surface)
246 | mSurfaceView.holder.addCallback(object : SurfaceHolder.Callback {
247 | override fun surfaceCreated(surfaceHolder: SurfaceHolder) {
248 | Log.d(TAG, "surfaceCreated")
249 | val frame = surfaceHolder.surfaceFrame
250 | openCamera(frame.width(), frame.height())
251 | }
252 |
253 | override fun surfaceChanged(surfaceHolder: SurfaceHolder, format: Int, width: Int, height: Int) {
254 | Log.d(TAG, "surfaceChanged $format $width $height")
255 | }
256 |
257 | override fun surfaceDestroyed(surfaceHolder: SurfaceHolder) {
258 | Log.d(TAG, "surfaceDestroyed")
259 | closeCamera()
260 | }
261 | })
262 | }
263 |
264 | override fun onActivityCreated(savedInstanceState: Bundle?) {
265 | super.onActivityCreated(savedInstanceState)
266 | mFile = File(activity.getExternalFilesDir(null), "pic.jpg")
267 | }
268 |
269 | override fun onResume() {
270 | super.onResume()
271 | startBackgroundThread()
272 | }
273 |
274 | override fun onPause() {
275 | closeCamera()
276 | stopBackgroundThread()
277 | countdownTimer.stop()
278 | super.onPause()
279 | }
280 |
281 | private fun requestCameraPermission() {
282 | if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.CAMERA)) {
283 | ConfirmationDialog().show(childFragmentManager, FRAGMENT_DIALOG)
284 | } else {
285 | ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.CAMERA),
286 | REQUEST_CAMERA_PERMISSION)
287 | }
288 | }
289 |
290 | override fun onRequestPermissionsResult(requestCode: Int, permissions: Array,
291 | grantResults: IntArray) {
292 | if (requestCode == REQUEST_CAMERA_PERMISSION) {
293 | if (grantResults.size != 1 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
294 | ErrorDialog.newInstance(getString(R.string.request_permission))
295 | .show(childFragmentManager, FRAGMENT_DIALOG)
296 | }
297 | } else {
298 | super.onRequestPermissionsResult(requestCode, permissions, grantResults)
299 | }
300 | }
301 |
302 | /**
303 | * Sets up member variables related to camera.
304 | *
305 | * @param width The width of available size for camera preview
306 | * @param height The height of available size for camera preview
307 | */
308 | private fun setUpCameraOutputs(width: Int, height: Int) {
309 | if (!StreamConfigurationMap.isOutputSupportedFor(SurfaceHolder::class.java)) {
310 | throw RuntimeException("SurfaceView not supported")
311 | }
312 |
313 | val activity = activity
314 | val manager = activity.getSystemService(Context.CAMERA_SERVICE) as CameraManager
315 | val cameraIds = manager.cameraIdList
316 | if (cameraIds.isEmpty()) {
317 | throw RuntimeException("No cameras found")
318 | }
319 | try {
320 | for (cameraId in cameraIds) {
321 | val characteristics = manager.getCameraCharacteristics(cameraId)
322 |
323 | // We don't use a front facing camera in this sample.
324 | val facing = characteristics.get(CameraCharacteristics.LENS_FACING)
325 | if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
326 | continue
327 | }
328 |
329 | val map = characteristics.get(
330 | CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP) ?: continue
331 |
332 | // For still image captures, we use the largest available size.
333 | val largest = Collections.max(
334 | Arrays.asList(*map.getOutputSizes(ImageFormat.JPEG)),
335 | CompareSizesByArea())
336 | Log.d(TAG, "Largest still image size: $largest")
337 | mImageReader = ImageReader.newInstance(largest.width, largest.height,
338 | ImageFormat.JPEG, /*maxImages*/2)
339 | mImageReader!!.setOnImageAvailableListener(
340 | mOnImageAvailableListener, mBackgroundHandler)
341 |
342 | // Find out if we need to swap dimension to get the preview size relative to sensor
343 | // coordinate.
344 | val displayRotation = activity.windowManager.defaultDisplay.rotation
345 |
346 | mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION)!!
347 | var swappedDimensions = false
348 | when (displayRotation) {
349 | Surface.ROTATION_0, Surface.ROTATION_180 ->
350 | if (mSensorOrientation == 90 || mSensorOrientation == 270) {
351 | swappedDimensions = true
352 | }
353 | Surface.ROTATION_90, Surface.ROTATION_270 ->
354 | if (mSensorOrientation == 0 || mSensorOrientation == 180) {
355 | swappedDimensions = true
356 | }
357 | else ->
358 | Log.e(TAG, "Display rotation is invalid: $displayRotation")
359 | }
360 |
361 | val displaySize = Point()
362 | activity.windowManager.defaultDisplay.getSize(displaySize)
363 | var rotatedPreviewWidth = width
364 | var rotatedPreviewHeight = height
365 | var maxPreviewWidth = displaySize.x
366 | var maxPreviewHeight = displaySize.y
367 |
368 | if (swappedDimensions) {
369 | rotatedPreviewWidth = height
370 | rotatedPreviewHeight = width
371 | maxPreviewWidth = displaySize.y
372 | maxPreviewHeight = displaySize.x
373 | }
374 |
375 | if (maxPreviewWidth > MAX_PREVIEW_WIDTH) {
376 | maxPreviewWidth = MAX_PREVIEW_WIDTH
377 | }
378 |
379 | if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) {
380 | maxPreviewHeight = MAX_PREVIEW_HEIGHT
381 | }
382 |
383 | // Danger, W.R.! Attempting to use too large a preview size could exceed the camera
384 | // bus' bandwidth limitation, resulting in gorgeous previews but the storage of
385 | // garbage capture data.
386 | val outputSizes = map.getOutputSizes(SurfaceHolder::class.java)
387 | for (size in outputSizes) {
388 | Log.d(TAG, "outputSize: $size")
389 | }
390 | val previewSize = chooseOptimalSize(outputSizes,
391 | rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth,
392 | maxPreviewHeight, largest)
393 | Log.d(TAG, "previewSize: $previewSize")
394 |
395 | // We fit the aspect ratio of TextureView to the size of preview we picked.
396 | val orientation = resources.configuration.orientation
397 | if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
398 | mSurfaceView.setAspectRatio(previewSize.width, previewSize.height)
399 | }
400 | else {
401 | mSurfaceView.setAspectRatio(previewSize.height, previewSize.width)
402 | }
403 |
404 | // Check if the flash is supported.
405 | val available = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE)
406 | mFlashSupported = available ?: false
407 |
408 | mCameraId = cameraId
409 | return
410 | }
411 | }
412 | catch (e: CameraAccessException) {
413 | Log.e(TAG, "", e)
414 | }
415 | catch (e: NullPointerException) {
416 | // Currently an NPE is thrown when the Camera2API is used but not supported on the
417 | // device this code runs.
418 | ErrorDialog.newInstance(getString(R.string.camera_error))
419 | .show(childFragmentManager, FRAGMENT_DIALOG)
420 | }
421 |
422 | }
423 |
424 | /**
425 | * Opens the camera specified by [Camera2BasicFragment.mCameraId].
426 | */
427 | private fun openCamera(width: Int, height: Int) {
428 | if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
429 | requestCameraPermission()
430 | return
431 | }
432 | setUpCameraOutputs(width, height)
433 | // configureTransform(width, height)
434 | val activity = activity
435 | val manager = activity.getSystemService(Context.CAMERA_SERVICE) as CameraManager
436 | try {
437 | if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
438 | throw RuntimeException("Time out waiting to lock camera opening.")
439 | }
440 | manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler)
441 | }
442 | catch (e: CameraAccessException) {
443 | Log.e(TAG, "", e)
444 | }
445 | catch (e: InterruptedException) {
446 | throw RuntimeException("Interrupted while trying to lock camera opening.", e)
447 | }
448 |
449 | }
450 |
451 | /**
452 | * Closes the current [CameraDevice].
453 | */
454 | private fun closeCamera() {
455 | try {
456 | mCameraOpenCloseLock.acquire()
457 | if (null != mCaptureSession) {
458 | mCaptureSession!!.close()
459 | mCaptureSession = null
460 | }
461 | if (null != mCameraDevice) {
462 | mCameraDevice!!.close()
463 | mCameraDevice = null
464 | }
465 | if (null != mImageReader) {
466 | mImageReader!!.close()
467 | mImageReader = null
468 | }
469 | }
470 | catch (e: InterruptedException) {
471 | throw RuntimeException("Interrupted while trying to lock camera closing.", e)
472 | }
473 | finally {
474 | mCameraOpenCloseLock.release()
475 | }
476 | }
477 |
478 | /**
479 | * Starts a background thread and its [Handler].
480 | */
481 | private fun startBackgroundThread() {
482 | mBackgroundThread = HandlerThread("CameraBackground")
483 | mBackgroundThread!!.start()
484 | mBackgroundHandler = Handler(mBackgroundThread!!.looper)
485 | }
486 |
487 | /**
488 | * Stops the background thread and its [Handler].
489 | */
490 | private fun stopBackgroundThread() {
491 | mBackgroundThread!!.quitSafely()
492 | try {
493 | mBackgroundThread!!.join()
494 | mBackgroundThread = null
495 | mBackgroundHandler = null
496 | }
497 | catch (e: InterruptedException) {
498 | Log.e(TAG, "", e)
499 | }
500 | }
501 |
502 | /**
503 | * Creates a new [CameraCaptureSession] for camera preview.
504 | */
505 | private fun createCameraPreviewSession() {
506 | try {
507 | // This is the output Surface we need to start preview.
508 | val surface = mSurfaceView.holder.surface
509 |
510 | // We set up a CaptureRequest.Builder with the output Surface.
511 | mPreviewRequestBuilder = mCameraDevice!!.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
512 | mPreviewRequestBuilder!!.addTarget(surface)
513 |
514 | // Here, we create a CameraCaptureSession for camera preview.
515 | mCameraDevice!!.createCaptureSession(Arrays.asList(surface, mImageReader!!.surface),
516 | object : CameraCaptureSession.StateCallback() {
517 |
518 | override fun onConfigured(cameraCaptureSession: CameraCaptureSession) {
519 | // The camera is already closed
520 | if (null == mCameraDevice) {
521 | return
522 | }
523 |
524 | // When the session is ready, we start displaying the preview.
525 | mCaptureSession = cameraCaptureSession
526 | try {
527 | // Auto focus should be continuous for camera preview.
528 | mPreviewRequestBuilder!!.set(CaptureRequest.CONTROL_AF_MODE,
529 | CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE)
530 | // Flash is automatically enabled when necessary.
531 | setAutoFlash(mPreviewRequestBuilder)
532 |
533 | // Finally, we start displaying the camera preview.
534 | mPreviewRequest = mPreviewRequestBuilder!!.build()
535 | mCaptureSession!!.setRepeatingRequest(mPreviewRequest!!,
536 | mCaptureCallback, mBackgroundHandler)
537 | }
538 | catch (e: CameraAccessException) {
539 | Log.e(TAG, "", e)
540 | }
541 |
542 | // start countdown here
543 | countdownTimer.start()
544 | }
545 |
546 | override fun onConfigureFailed(
547 | cameraCaptureSession: CameraCaptureSession) {
548 | Log.e(TAG, "createCaptureSession failed")
549 | showToast("Failed")
550 | }
551 | }, null
552 | )
553 | }
554 | catch (e: CameraAccessException) {
555 | Log.e(TAG, "", e)
556 | }
557 | }
558 |
559 | /**
560 | * Initiate a still image capture.
561 | */
562 | private fun takePicture() {
563 | lockFocus()
564 | }
565 |
566 | /**
567 | * Lock the focus as the first step for a still image capture.
568 | */
569 | private fun lockFocus() {
570 | try {
571 | // This is how to tell the camera to lock focus.
572 | mPreviewRequestBuilder!!.set(CaptureRequest.CONTROL_AF_TRIGGER,
573 | CameraMetadata.CONTROL_AF_TRIGGER_START)
574 | // Tell #mCaptureCallback to wait for the lock.
575 | mState = STATE_WAITING_LOCK
576 | mCaptureSession!!.capture(mPreviewRequestBuilder!!.build(), mCaptureCallback,
577 | mBackgroundHandler)
578 | }
579 | catch (e: CameraAccessException) {
580 | Log.e(TAG, "", e)
581 | }
582 | }
583 |
584 | /**
585 | * Capture a still picture. This method should be called when we get a response in
586 | * [.mCaptureCallback] from both [.lockFocus].
587 | */
588 | private fun captureStillPicture() {
589 | try {
590 | val activity = activity
591 | if (null == activity || null == mCameraDevice) {
592 | return
593 | }
594 | // This is the CaptureRequest.Builder that we use to take a picture.
595 | val captureBuilder = mCameraDevice!!.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE)
596 | captureBuilder.addTarget(mImageReader!!.surface)
597 |
598 | // Use the same AE and AF modes as the preview.
599 | captureBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE)
600 | setAutoFlash(captureBuilder)
601 |
602 | // Orientation
603 | val rotation = activity.windowManager.defaultDisplay.rotation
604 | captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, getOrientation(rotation))
605 |
606 | mCaptureSession!!.stopRepeating()
607 | mCaptureSession!!.capture(captureBuilder.build(), captureCallback, null)
608 | }
609 | catch (e: CameraAccessException) {
610 | Log.e(TAG, "", e)
611 | }
612 |
613 | }
614 |
615 | /**
616 | * Retrieves the JPEG orientation from the specified screen rotation.
617 | *
618 | * @param rotation The screen rotation.
619 | * @return The JPEG orientation (one of 0, 90, 270, and 360)
620 | */
621 | private fun getOrientation(rotation: Int): Int {
622 | // Sensor orientation is 90 for most devices, or 270 for some devices (eg. Nexus 5X)
623 | // We have to take that into account and rotate JPEG properly.
624 | // For devices with orientation of 90, we simply return our mapping from ORIENTATIONS.
625 | // For devices with orientation of 270, we need to rotate the JPEG 180 degrees.
626 | return (ORIENTATIONS.get(rotation) + mSensorOrientation + 270) % 360
627 | }
628 |
629 | /**
630 | * Unlock the focus. This method should be called when still image capture sequence is
631 | * finished.
632 | */
633 | private fun unlockFocus() {
634 | try {
635 | // Reset the auto-focus trigger
636 | mPreviewRequestBuilder!!.set(CaptureRequest.CONTROL_AF_TRIGGER,
637 | CameraMetadata.CONTROL_AF_TRIGGER_CANCEL)
638 | setAutoFlash(mPreviewRequestBuilder)
639 | mCaptureSession!!.capture(mPreviewRequestBuilder!!.build(), mCaptureCallback,
640 | mBackgroundHandler)
641 | // After this, the camera will go back to the normal state of preview.
642 | mState = STATE_PREVIEW
643 | mCaptureSession!!.setRepeatingRequest(mPreviewRequest!!, mCaptureCallback,
644 | mBackgroundHandler)
645 | }
646 | catch (e: CameraAccessException) {
647 | Log.e(TAG, "", e)
648 | }
649 |
650 | }
651 |
652 | override fun onClick(view: View) {
653 | Log.d(TAG, "onClick")
654 | when (view.id) {
655 | R.id.picture -> {
656 | takePicture()
657 | }
658 | R.id.back -> {
659 | activity.finish()
660 | }
661 | }
662 | }
663 |
664 | private fun setAutoFlash(requestBuilder: CaptureRequest.Builder?) {
665 | if (mFlashSupported) {
666 | requestBuilder!!.set(CaptureRequest.CONTROL_AE_MODE,
667 | CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH)
668 | }
669 | }
670 |
671 | override fun onCount(value: Int) {
672 | tvTimer.text = String.format("%d", value)
673 | if (value == 0) {
674 | takePicture()
675 | }
676 | }
677 |
678 |
679 | /**
680 | * Saves a JPEG [Image] into the specified [File].
681 | */
682 | private class ImageSaver(
683 | private val mImage: Image,
684 | private val mFile: File) : Runnable {
685 |
686 | override fun run() {
687 | val buffer = mImage.planes[0].buffer
688 | val bytes = ByteArray(buffer.remaining())
689 | buffer.get(bytes)
690 |
691 | try {
692 | mImage.use {
693 | FileOutputStream(mFile).use {
694 | it.write(bytes)
695 | }
696 | }
697 | }
698 | catch (e: Exception) {
699 | Log.e(TAG, "Error writing image to $mFile", e)
700 | }
701 | }
702 |
703 | }
704 |
705 | /**
706 | * Compares two `Size`s based on their areas.
707 | */
708 | internal class CompareSizesByArea : Comparator {
709 | override fun compare(lhs: Size, rhs: Size): Int {
710 | // We cast here to ensure the multiplications won't overflow
711 | return java.lang.Long.signum(lhs.width.toLong() * lhs.height - rhs.width.toLong() * rhs.height)
712 | }
713 | }
714 |
715 | /**
716 | * Shows an error message dialog.
717 | */
718 | class ErrorDialog : DialogFragment() {
719 | override fun onCreateDialog(savedInstanceState: Bundle): Dialog {
720 | val activity = activity
721 | return AlertDialog.Builder(activity)
722 | .setMessage(arguments.getString(ARG_MESSAGE))
723 | .setPositiveButton(android.R.string.ok) { _, _ -> activity.finish() }
724 | .create()
725 | }
726 |
727 | companion object {
728 | private const val ARG_MESSAGE = "message"
729 |
730 | fun newInstance(message: String): ErrorDialog {
731 | val dialog = ErrorDialog()
732 | val args = Bundle()
733 | args.putString(ARG_MESSAGE, message)
734 | dialog.arguments = args
735 | return dialog
736 | }
737 | }
738 | }
739 |
740 | /**
741 | * Shows OK/Cancel confirmation dialog about camera permission.
742 | */
743 | class ConfirmationDialog : DialogFragment() {
744 | override fun onCreateDialog(savedInstanceState: Bundle): Dialog {
745 | return AlertDialog.Builder(activity)
746 | .setMessage(R.string.request_permission)
747 | .setPositiveButton(android.R.string.ok) { _, _ ->
748 | ActivityCompat.requestPermissions(activity,
749 | arrayOf(Manifest.permission.CAMERA),
750 | REQUEST_CAMERA_PERMISSION)
751 | }
752 | .setNegativeButton(android.R.string.cancel) { _, _ ->
753 | activity.finish()
754 | }
755 | .create()
756 | }
757 | }
758 |
759 | companion object {
760 |
761 | /**
762 | * Conversion from screen rotation to JPEG orientation.
763 | */
764 | private val ORIENTATIONS = SparseIntArray()
765 | private const val REQUEST_CAMERA_PERMISSION = 1
766 | private const val FRAGMENT_DIALOG = "dialog"
767 |
768 | init {
769 | ORIENTATIONS.append(Surface.ROTATION_0, 90)
770 | ORIENTATIONS.append(Surface.ROTATION_90, 0)
771 | ORIENTATIONS.append(Surface.ROTATION_180, 270)
772 | ORIENTATIONS.append(Surface.ROTATION_270, 180)
773 | }
774 |
775 | /**
776 | * Tag for the [Log].
777 | */
778 | private const val TAG = "Camera2BasicFragment"
779 |
780 | /**
781 | * Camera state: Showing camera preview.
782 | */
783 | private const val STATE_PREVIEW = 0
784 |
785 | /**
786 | * Camera state: Waiting for the focus to be locked.
787 | */
788 | private const val STATE_WAITING_LOCK = 1
789 |
790 | /**
791 | * Camera state: Waiting for the exposure to be precapture state.
792 | */
793 | private const val STATE_WAITING_PRECAPTURE = 2
794 |
795 | /**
796 | * Camera state: Waiting for the exposure state to be something other than precapture.
797 | */
798 | private const val STATE_WAITING_NON_PRECAPTURE = 3
799 |
800 | /**
801 | * Camera state: Picture was taken.
802 | */
803 | private const val STATE_PICTURE_TAKEN = 4
804 |
805 | /**
806 | * Max preview width that is guaranteed by Camera2 API
807 | */
808 | private const val MAX_PREVIEW_WIDTH = 1920
809 |
810 | /**
811 | * Max preview height that is guaranteed by Camera2 API
812 | */
813 | private const val MAX_PREVIEW_HEIGHT = 1080
814 |
815 | /**
816 | * Given `choices` of `Size`s supported by a camera, choose the smallest one that
817 | * is at least as large as the respective texture view size, and that is at most as large as the
818 | * respective max size, and whose aspect ratio matches with the specified value. If such size
819 | * doesn't exist, choose the largest one that is at most as large as the respective max size,
820 | * and whose aspect ratio matches with the specified value.
821 | *
822 | * @param choices The list of sizes that the camera supports for the intended output
823 | * class
824 | * @param textureViewWidth The width of the texture view relative to sensor coordinate
825 | * @param textureViewHeight The height of the texture view relative to sensor coordinate
826 | * @param maxWidth The maximum width that can be chosen
827 | * @param maxHeight The maximum height that can be chosen
828 | * @param aspectRatio The aspect ratio
829 | * @return The optimal `Size`, or an arbitrary one if none were big enough
830 | */
831 | private fun chooseOptimalSize(choices: Array, textureViewWidth: Int,
832 | textureViewHeight: Int, maxWidth: Int, maxHeight: Int,
833 | aspectRatio: Size): Size {
834 |
835 | // Collect the supported resolutions that are at least as big as the preview Surface
836 | val bigEnough = ArrayList()
837 | // Collect the supported resolutions that are smaller than the preview Surface
838 | val notBigEnough = ArrayList()
839 | val w = aspectRatio.width
840 | val h = aspectRatio.height
841 | for (option in choices) {
842 | if (option.width <= maxWidth && option.height <= maxHeight &&
843 | option.height == option.width * h / w) {
844 | if (option.width >= textureViewWidth && option.height >= textureViewHeight) {
845 | bigEnough.add(option)
846 | }
847 | else {
848 | notBigEnough.add(option)
849 | }
850 | }
851 | }
852 |
853 | // Pick the smallest of those big enough. If there is no one big enough, pick the
854 | // largest of those not big enough.
855 | return when {
856 | bigEnough.size > 0 -> {
857 | Collections.min(bigEnough, CompareSizesByArea())
858 | }
859 | notBigEnough.size > 0 -> {
860 | Collections.max(notBigEnough, CompareSizesByArea())
861 | }
862 | else -> {
863 | Log.e(TAG, "Couldn't find any suitable preview size")
864 | choices[0]
865 | }
866 | }
867 | }
868 |
869 | fun newInstance(): Camera2BasicFragment {
870 | return Camera2BasicFragment()
871 | }
872 | }
873 |
874 | }
875 |
--------------------------------------------------------------------------------
/thing/src/main/java/com/hyperaware/doorbell/thing/activity/CountdownTimer.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.hyperaware.doorbell.thing.activity
18 |
19 | import android.os.Handler
20 |
21 | class CountdownTimer(private var count: Int, private val listener: Listener) {
22 |
23 | private val handler = Handler()
24 | private val runnable = CountdownRunnable()
25 |
26 | interface Listener {
27 | fun onCount(value: Int)
28 | }
29 |
30 | fun start() {
31 | handler.post(runnable)
32 | }
33 |
34 | fun stop() {
35 | handler.removeCallbacks(runnable)
36 | }
37 |
38 | private inner class CountdownRunnable : Runnable {
39 | override fun run() {
40 | listener.onCount(count)
41 | if (count > 0) {
42 | count--
43 | handler.postDelayed(runnable, 1000)
44 | }
45 | }
46 | }
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/thing/src/main/java/com/hyperaware/doorbell/thing/activity/NearbyConnectionsActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.hyperaware.doorbell.thing.activity
18 |
19 | import android.app.Activity
20 | import android.net.ConnectivityManager
21 | import android.net.Network
22 | import android.os.Bundle
23 | import android.util.Log
24 | import com.google.android.gms.nearby.Nearby
25 | import com.google.android.gms.nearby.connection.*
26 | import com.google.firebase.auth.FirebaseAuth
27 | import com.google.firebase.auth.GoogleAuthProvider
28 |
29 | class NearbyConnectionsActivity : Activity() {
30 |
31 | companion object {
32 | private const val TAG = "NearbyConnectionsActivity"
33 | }
34 |
35 | private lateinit var connectivityManager : ConnectivityManager
36 | private lateinit var connectionsClient: ConnectionsClient
37 | private var token : String? = null
38 |
39 | private val networkCallback = object : ConnectivityManager.NetworkCallback() {
40 | override fun onAvailable(network: Network?) {
41 | super.onAvailable(network)
42 | Log.d(TAG, "onAvailable $network")
43 | if (token != null) {
44 | trySignIn()
45 | }
46 | }
47 |
48 | override fun onLost(network: Network?) {
49 | Log.d(TAG, "onLost $network")
50 | }
51 | }
52 |
53 | override fun onCreate(savedInstanceState: Bundle?) {
54 | super.onCreate(savedInstanceState)
55 | connectionsClient = Nearby.getConnectionsClient(this)
56 |
57 | connectivityManager = getSystemService(ConnectivityManager::class.java)
58 | connectivityManager.registerDefaultNetworkCallback(networkCallback)
59 |
60 | FirebaseAuth.getInstance().signOut()
61 | }
62 |
63 | override fun onStart() {
64 | super.onStart()
65 | startAdvertising()
66 | }
67 |
68 | override fun onStop() {
69 | stopAdvertising()
70 | super.onStop()
71 | }
72 |
73 | override fun onDestroy() {
74 | connectionsClient.stopAllEndpoints()
75 | connectivityManager.unregisterNetworkCallback(networkCallback)
76 | super.onDestroy()
77 | }
78 |
79 | private fun startAdvertising() {
80 | connectionsClient.startAdvertising(
81 | "Firebase Doorbell Thing",
82 | packageName,
83 | connectionLifecycleCallback,
84 | AdvertisingOptions.Builder().setStrategy(Strategy.P2P_CLUSTER).build()
85 | )
86 | .addOnSuccessListener(this) {
87 | Log.d(TAG, "startAdvertising onSuccess")
88 | }
89 | .addOnFailureListener(this) { e ->
90 | Log.e(TAG, "startAdvertising onFailure", e)
91 | }
92 | }
93 |
94 | private fun stopAdvertising() {
95 | connectionsClient.stopAdvertising()
96 | }
97 |
98 | private val connectionLifecycleCallback = object : ConnectionLifecycleCallback() {
99 | override fun onConnectionInitiated(endpointId: String, info: ConnectionInfo) {
100 | Log.d(TAG, "onConnectionInitiated $endpointId name: ${info.endpointName}")
101 | connectionsClient.acceptConnection(endpointId, payloadCallback)
102 | .addOnSuccessListener(this@NearbyConnectionsActivity) { _ ->
103 | Log.d(TAG, "acceptConnection onSuccess")
104 | }
105 | .addOnFailureListener(this@NearbyConnectionsActivity) { e ->
106 | Log.e(TAG, "acceptConnection onFailure", e)
107 | }
108 | }
109 |
110 | override fun onConnectionResult(endpointId: String, resolution: ConnectionResolution) {
111 | Log.d(TAG, "onConnectionResult $endpointId status: ${resolution.status}")
112 | }
113 |
114 | override fun onDisconnected(endpointId: String) {
115 | Log.d(TAG, "onDisconnected $endpointId")
116 | trySignIn()
117 | }
118 | }
119 |
120 | private val payloadCallback = object : PayloadCallback() {
121 | override fun onPayloadReceived(endpointId: String, payload: Payload) {
122 | Log.d(TAG, "onPayloadReceived $endpointId payload: ${payload.id}")
123 | token = String(payload.asBytes()!!)
124 | Log.d(TAG, token)
125 | }
126 |
127 | override fun onPayloadTransferUpdate(endpointId: String, update: PayloadTransferUpdate) {
128 | Log.d(TAG, "onPayloadTransferUpdate $endpointId ${update.status}")
129 | }
130 | }
131 |
132 | private fun trySignIn() {
133 | Log.d(TAG, "Signing in with token $token")
134 | val credential = GoogleAuthProvider.getCredential(token, null)
135 | FirebaseAuth.getInstance().signInWithCredential(credential)
136 | .addOnSuccessListener(this) { result ->
137 | val user = result.user
138 | Log.d(TAG, "signInWithCredential ${user.displayName} ${user.email}")
139 | finish()
140 | }
141 | .addOnFailureListener(this) { e ->
142 | Log.e(TAG, "signInWithCredential onFailure", e)
143 | }
144 | }
145 |
146 | }
147 |
--------------------------------------------------------------------------------
/thing/src/main/java/com/hyperaware/doorbell/thing/activity/NearbyMessagingActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.hyperaware.doorbell.thing.activity
18 |
19 | import android.app.Activity
20 | import android.os.Bundle
21 | import android.os.Handler
22 | import android.util.Log
23 | import android.widget.TextView
24 | import com.google.android.gms.nearby.Nearby
25 | import com.google.android.gms.nearby.messages.*
26 | import com.google.firebase.auth.FirebaseAuth
27 | import com.google.firebase.auth.GoogleAuthProvider
28 | import com.hyperaware.doorbell.thing.R
29 | import com.hyperaware.doorbell.thing.activity.NearbyMessagingActivity.UiState.*
30 |
31 | class NearbyMessagingActivity : Activity() {
32 |
33 | companion object {
34 | private const val TAG = "NearbyMessagingActivity"
35 | }
36 |
37 | private val handler = Handler()
38 |
39 | private lateinit var tvStatus: TextView
40 |
41 | private lateinit var client: MessagesClient
42 | private var token : String? = null
43 |
44 | override fun onCreate(savedInstanceState: Bundle?) {
45 | super.onCreate(savedInstanceState)
46 |
47 | setContentView(R.layout.activity_auth)
48 | tvStatus = findViewById(R.id.tvStatus)
49 | updateUi(WaitingForPermission)
50 |
51 | client = Nearby.getMessagesClient(this)
52 | }
53 |
54 | override fun onStart() {
55 | super.onStart()
56 |
57 | client.registerStatusCallback(statusCallback)
58 | }
59 |
60 | override fun onStop() {
61 | client.unsubscribe(messageListener)
62 | client.unregisterStatusCallback(statusCallback)
63 |
64 | super.onStop()
65 | }
66 |
67 | private enum class UiState {
68 | WaitingForPermission,
69 | Subscribing,
70 | SubscribeExpired,
71 | SubscriptionFailure,
72 | WaitingForMessage,
73 | Authenticating,
74 | MessageTimedOut,
75 | SignInFailed
76 | }
77 |
78 | private fun updateUi(uiState: UiState, finishOnDelay: Boolean = false) {
79 | Log.d(TAG, "uiState: $uiState")
80 | val message = when (uiState) {
81 | WaitingForPermission -> "Waiting for permission..."
82 | Subscribing -> "Subscribing..."
83 | SubscribeExpired -> "Nearby Messaging subscription expired."
84 | SubscriptionFailure -> "Subscription failure"
85 | WaitingForMessage -> "Waiting for message..."
86 | Authenticating -> "Found nearby message, authenticating..."
87 | MessageTimedOut -> "Timed out waiting for message."
88 | SignInFailed -> "Sign in failed."
89 | }
90 |
91 | tvStatus.text = message
92 | if (finishOnDelay) {
93 | handler.postDelayed({ finish() }, 2000)
94 | }
95 | }
96 |
97 | private val statusCallback = object : StatusCallback() {
98 | override fun onPermissionChanged(permissionGranted: Boolean) {
99 | Log.d(TAG, "onPermissionChanged $permissionGranted")
100 | updateUi(Subscribing)
101 | subscribe()
102 | }
103 | }
104 |
105 | private fun subscribe() {
106 | val strategy = Strategy.Builder()
107 | .setDiscoveryMode(Strategy.DISCOVERY_MODE_SCAN)
108 | .setTtlSeconds(Strategy.TTL_SECONDS_MAX)
109 | .build()
110 |
111 | val subscribeOpts = SubscribeOptions.Builder()
112 | .setStrategy(strategy)
113 | .setCallback(object : SubscribeCallback() {
114 | override fun onExpired() {
115 | Log.d(TAG, "onExpired")
116 | updateUi(SubscribeExpired, true)
117 | }
118 | })
119 | .build()
120 |
121 | client.subscribe(messageListener, subscribeOpts)
122 | .addOnSuccessListener(this) {
123 | Log.d(TAG, "subscribe success")
124 | updateUi(WaitingForMessage)
125 | handler.postDelayed({ updateUi(MessageTimedOut, true) }, 30000)
126 | }
127 | .addOnFailureListener(this) { e ->
128 | Log.e(TAG, "subscribe failure", e)
129 | updateUi(SubscriptionFailure, true)
130 | }
131 | }
132 |
133 | private val messageListener = object : MessageListener() {
134 | override fun onFound(message: Message) {
135 | token = String(message.content)
136 | Log.d(TAG, "Found message: $token")
137 | updateUi(Authenticating, true)
138 | trySignIn()
139 | }
140 |
141 | override fun onLost(message: Message) {
142 | Log.d(TAG, "Lost message: " + String(message.content))
143 | }
144 | }
145 |
146 | private fun trySignIn() {
147 | Log.d(TAG, "Signing in with token $token")
148 | val credential = GoogleAuthProvider.getCredential(token, null)
149 | FirebaseAuth.getInstance().signInWithCredential(credential)
150 | .addOnSuccessListener(this) { result ->
151 | val user = result.user
152 | Log.d(TAG, "signInWithCredential ${user.displayName} ${user.email}")
153 | finish()
154 | }
155 | .addOnFailureListener(this) { e ->
156 | Log.e(TAG, "signInWithCredential onFailure", e)
157 | }
158 | }
159 |
160 | }
161 |
--------------------------------------------------------------------------------
/thing/src/main/java/com/hyperaware/doorbell/thing/activity/ResponseActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.hyperaware.doorbell.thing.activity
18 |
19 | import android.app.Activity
20 | import android.os.Bundle
21 | import android.os.Handler
22 | import android.util.Log
23 | import android.widget.TextView
24 | import com.hyperaware.doorbell.thing.R
25 |
26 | class ResponseActivity : Activity() {
27 |
28 | companion object {
29 | private const val TAG = "ResponseActivity"
30 | const val EXTRA_DISPOSITION = "disposition"
31 | }
32 |
33 | private lateinit var tvDisposition: TextView
34 | private var disposition: Boolean = false
35 |
36 | override fun onCreate(savedInstanceState: Bundle?) {
37 | super.onCreate(savedInstanceState)
38 | val intent = intent
39 |
40 | val extras = intent.extras
41 | if (extras == null || !extras.containsKey(EXTRA_DISPOSITION)) {
42 | Log.e(TAG, "$EXTRA_DISPOSITION was not provided")
43 | finish()
44 | return
45 | }
46 |
47 | disposition = extras.getBoolean(EXTRA_DISPOSITION)
48 |
49 | initViews()
50 | Handler().postDelayed({ finish() }, 5000)
51 | }
52 |
53 | private fun initViews() {
54 | setContentView(R.layout.activity_response)
55 | tvDisposition = findViewById(R.id.disposition)
56 | tvDisposition.text = if (disposition) {
57 | getString(R.string.disposition_come_in)
58 | }
59 | else {
60 | getString(R.string.disposition_go_away)
61 | }
62 | }
63 |
64 | }
65 |
--------------------------------------------------------------------------------
/thing/src/main/java/com/hyperaware/doorbell/thing/activity/TestMainActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.hyperaware.doorbell.thing.activity
18 |
19 | import android.app.Activity
20 | import android.content.Intent
21 | import android.os.Bundle
22 | import android.widget.Button
23 | import com.google.firebase.auth.FirebaseAuth
24 | import com.google.firebase.auth.FirebaseUser
25 | import com.hyperaware.doorbell.thing.R
26 |
27 | class TestMainActivity : Activity() {
28 |
29 | private val auth = FirebaseAuth.getInstance()
30 | private var user: FirebaseUser? = null
31 |
32 | private lateinit var vMain: Button
33 | private lateinit var vAuthConns: Button
34 | private lateinit var vAuthMessaging: Button
35 | private lateinit var vSignOut: Button
36 |
37 | override fun onCreate(savedInstanceState: Bundle?) {
38 | super.onCreate(savedInstanceState)
39 | setContentView(R.layout.activity_test_main)
40 |
41 | vMain = findViewById(R.id.btn_main)
42 | vMain.setOnClickListener {
43 | startActivity(Intent(this, MainActivity::class.java))
44 | }
45 |
46 | vAuthConns = findViewById(R.id.btn_auth_conns)
47 | vAuthConns.setOnClickListener {
48 | startActivity(Intent(this, NearbyConnectionsActivity::class.java))
49 | }
50 |
51 | vAuthMessaging = findViewById(R.id.btn_auth_messaging)
52 | vAuthMessaging.setOnClickListener {
53 | startActivity(Intent(this, NearbyMessagingActivity::class.java))
54 | }
55 |
56 | vSignOut = findViewById(R.id.btn_sign_out)
57 | vSignOut.setOnClickListener {
58 | auth.signOut()
59 | }
60 |
61 | updateUi()
62 | }
63 |
64 | override fun onStart() {
65 | super.onStart()
66 | auth.addAuthStateListener(authStateListener)
67 | }
68 |
69 | override fun onStop() {
70 | auth.removeAuthStateListener(authStateListener)
71 | super.onStop()
72 | }
73 |
74 | private val authStateListener = FirebaseAuth.AuthStateListener {
75 | user = auth.currentUser
76 | updateUi()
77 | }
78 |
79 | private fun updateUi() {
80 | vMain.isEnabled = user != null
81 | vAuthConns.isEnabled = user == null
82 | vAuthMessaging.isEnabled = user == null
83 | vSignOut.isEnabled = user != null
84 | }
85 |
86 | }
87 |
--------------------------------------------------------------------------------
/thing/src/main/java/com/hyperaware/doorbell/thing/fcm/MyInstanceIdService.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.hyperaware.doorbell.thing.fcm
18 |
19 | import android.util.Log
20 |
21 | import com.google.firebase.iid.FirebaseInstanceId
22 | import com.google.firebase.iid.FirebaseInstanceIdService
23 | import com.google.firebase.messaging.FirebaseMessaging
24 |
25 | class MyInstanceIdService : FirebaseInstanceIdService() {
26 |
27 | companion object {
28 | private const val TAG = "MyInstanceIdService"
29 | }
30 |
31 | override fun onTokenRefresh() {
32 | super.onTokenRefresh()
33 | Log.d(TAG, "FCM token refresh: ${FirebaseInstanceId.getInstance().token!!}")
34 | FirebaseMessaging.getInstance().subscribeToTopic("answers")
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/thing/src/main/java/com/hyperaware/doorbell/thing/fcm/OnAnswerMessagingService.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.hyperaware.doorbell.thing.fcm
18 |
19 | import android.content.Intent
20 | import android.util.Log
21 | import com.google.firebase.messaging.FirebaseMessagingService
22 | import com.google.firebase.messaging.RemoteMessage
23 | import com.hyperaware.doorbell.thing.activity.ResponseActivity
24 |
25 | class OnAnswerMessagingService : FirebaseMessagingService() {
26 |
27 | companion object {
28 | private const val TAG = "AnswerMessagingService"
29 | private const val PROP_DISPOSITION = "disposition"
30 | }
31 |
32 | override fun onMessageReceived(remoteMessage: RemoteMessage) {
33 | super.onMessageReceived(remoteMessage)
34 | Log.d(TAG, "Answer message received")
35 |
36 | //
37 | // The incoming message should contain the response from the companion app
38 | //
39 |
40 | if (remoteMessage.data.containsKey(PROP_DISPOSITION)) {
41 | val disposition = java.lang.Boolean.parseBoolean(remoteMessage.data[PROP_DISPOSITION])
42 | Log.d(TAG, "$PROP_DISPOSITION: $disposition")
43 | val intent = Intent(this, ResponseActivity::class.java)
44 | intent.putExtra(ResponseActivity.EXTRA_DISPOSITION, disposition)
45 | startActivity(intent)
46 | }
47 | else {
48 | Log.w(TAG, "Data message received without $PROP_DISPOSITION")
49 | }
50 | }
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/thing/src/main/res/layout/activity_auth.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/thing/src/main/res/layout/activity_camera.xml:
--------------------------------------------------------------------------------
1 |
16 |
23 |
--------------------------------------------------------------------------------
/thing/src/main/res/layout/activity_response.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/thing/src/main/res/layout/activity_test_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
11 |
12 |
17 |
18 |
23 |
24 |
29 |
30 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/thing/src/main/res/layout/camera.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/thing/src/main/res/layout/fragment_camera2_basic.xml:
--------------------------------------------------------------------------------
1 |
16 |
20 |
21 |
27 |
28 |
37 |
38 |
44 |
45 |
50 |
51 |
59 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/thing/src/main/res/layout/main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
18 |
19 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/thing/src/main/res/layout/thing.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/thing/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/thing/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | Firebase Doorbell Thing
4 |
5 | This sample needs camera permission.
6 | This device doesn\'t support Camera2 API.
7 |
8 | COME ON IN!
9 | GO AWAY!
10 |
11 |
12 |
--------------------------------------------------------------------------------
/thing/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/thing/src/realThing/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/thing/src/realThing/java/com/hyperaware/doorbell/thing/activity/MainActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.hyperaware.doorbell.thing.activity
18 |
19 | import android.os.Bundle
20 | import android.util.Log
21 | import android.view.View
22 |
23 | import com.google.android.things.contrib.driver.button.Button
24 | import com.google.android.things.contrib.driver.rainbowhat.RainbowHat
25 | import com.google.android.things.pio.Gpio
26 | import java.io.Closeable
27 |
28 | import java.io.IOException
29 |
30 | class MainActivity : BaseMainActivity() {
31 |
32 | companion object {
33 | private const val TAG = "MainActivity"
34 | }
35 |
36 | private var buttonA: Button? = null
37 | private var buttonB: Button? = null
38 | private var buttonC: Button? = null
39 | private var red: Gpio? = null
40 | private var green: Gpio? = null
41 | private var blue: Gpio? = null
42 |
43 | override fun onCreate(savedInstanceState: Bundle?) {
44 | super.onCreate(savedInstanceState)
45 | try {
46 | initThing()
47 | }
48 | catch (e: IOException) {
49 | Log.e(TAG, "Error initializing Thing hardware", e)
50 | finish()
51 | }
52 |
53 | buttonRing.visibility = View.GONE
54 | }
55 |
56 | override fun onDestroy() {
57 | closeThing()
58 | super.onDestroy()
59 | }
60 |
61 | @Throws(IOException::class)
62 | private fun initThing() {
63 | initLeds()
64 | initButtons()
65 | }
66 |
67 | @Throws(IOException::class)
68 | private fun initLeds() {
69 | red = RainbowHat.openLedRed()
70 | red!!.value = false
71 | green = RainbowHat.openLedGreen()
72 | green!!.value = false
73 | blue = RainbowHat.openLedBlue()
74 | blue!!.value = false
75 | }
76 |
77 | @Throws(IOException::class)
78 | private fun initButtons() {
79 | buttonA = RainbowHat.openButtonA()
80 | buttonA!!.setOnButtonEventListener { _, pressed ->
81 | Log.i(TAG, "Button A $pressed")
82 | if (pressed) {
83 | onRingClick()
84 | }
85 | try {
86 | red!!.value = pressed
87 | }
88 | catch (e: IOException) {
89 | Log.e(TAG, "", e)
90 | }
91 | }
92 | buttonB = RainbowHat.openButtonB()
93 | buttonB!!.setOnButtonEventListener { _, pressed ->
94 | Log.i(TAG, "Button B $pressed")
95 | try {
96 | green!!.value = pressed
97 | }
98 | catch (e: IOException) {
99 | Log.e(TAG, "", e)
100 | }
101 | }
102 | buttonC = RainbowHat.openButtonC()
103 | buttonC!!.setOnButtonEventListener { _, pressed ->
104 | Log.i(TAG, "Button C $pressed")
105 | if (pressed) {
106 | finish()
107 | }
108 | try {
109 | blue!!.value = pressed
110 | }
111 | catch (e: IOException) {
112 | Log.e(TAG, "", e)
113 | }
114 | }
115 | }
116 |
117 | private fun closeThing() {
118 | closeLeds()
119 | closeButtons()
120 | }
121 |
122 | private fun closeLeds() {
123 | safeClose(red)
124 | safeClose(green)
125 | safeClose(blue)
126 | }
127 |
128 | private fun closeButtons() {
129 | safeClose(buttonA)
130 | safeClose(buttonB)
131 | safeClose(buttonC)
132 | }
133 |
134 | private fun safeClose(closeable: Gpio?) {
135 | try {
136 | closeable?.close()
137 | }
138 | catch (e: IOException) {
139 | Log.e(TAG, "", e)
140 | }
141 | }
142 |
143 | private fun safeClose(closeable: AutoCloseable?) {
144 | try {
145 | closeable?.close()
146 | }
147 | catch (e: IOException) {
148 | Log.e(TAG, "", e)
149 | }
150 | }
151 |
152 | }
153 |
--------------------------------------------------------------------------------