Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

First start on QR scanner for Android

Michael Rademaker345b2a9e30d0
diff --git a/console/android/ORLib/build.gradle b/console/android/ORLib/build.gradle
index 742c051c9..123b08e89 100644
--- a/console/android/ORLib/build.gradle
+++ b/console/android/ORLib/build.gradle
@@ -46,4 +46,8 @@ dependencies {
implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.9.8"
implementation platform('com.google.firebase:firebase-bom:26.0.0')
implementation 'com.google.firebase:firebase-messaging-ktx'
+ implementation 'androidx.camera:camera-core:1.1.0-alpha03'
+ implementation 'androidx.camera:camera-lifecycle:1.1.0-alpha03'
+ implementation 'com.google.mlkit:vision-common:16.3.0'
+ implementation 'com.google.android.gms:play-services-mlkit-barcode-scanning:16.2.1'
}
\ No newline at end of file
diff --git a/console/android/ORLib/src/main/java/io/openremote/orlib/service/QrScannerProvider.kt b/console/android/ORLib/src/main/java/io/openremote/orlib/service/QrScannerProvider.kt
new file mode 100644
index 000000000..88ef87ff4
--- /dev/null
+++ b/console/android/ORLib/src/main/java/io/openremote/orlib/service/QrScannerProvider.kt
@@ -0,0 +1,4 @@
+package io.openremote.orlib.service
+
+class QrScannerProvider {
+}
\ No newline at end of file
diff --git a/console/android/ORLib/src/main/java/io/openremote/orlib/ui/QrScannerActivity.kt b/console/android/ORLib/src/main/java/io/openremote/orlib/ui/QrScannerActivity.kt
new file mode 100644
index 000000000..059d94c7d
--- /dev/null
+++ b/console/android/ORLib/src/main/java/io/openremote/orlib/ui/QrScannerActivity.kt
@@ -0,0 +1,235 @@
+package io.openremote.orlib.ui
+
+import android.Manifest
+import android.annotation.SuppressLint
+import android.app.Activity
+import android.content.pm.PackageManager
+import android.net.Uri
+import android.os.Bundle
+import android.util.Log
+import android.widget.Toast
+import androidx.camera.core.*
+import androidx.camera.lifecycle.ProcessCameraProvider
+import androidx.core.app.ActivityCompat
+import androidx.core.content.ContextCompat
+import com.google.mlkit.vision.barcode.Barcode
+import com.google.mlkit.vision.barcode.BarcodeScannerOptions
+import com.google.mlkit.vision.barcode.BarcodeScanning
+import com.google.mlkit.vision.common.InputImage
+import io.openremote.orlib.databinding.ActivityOrMainBinding
+import io.openremote.orlib.databinding.ActivityOrQrScannerBinding
+import java.io.File
+import java.nio.ByteBuffer
+import java.text.SimpleDateFormat
+import java.util.*
+import java.util.concurrent.ExecutorService
+import java.util.concurrent.Executors
+
+typealias QrListener = (qrValue: String) -> Unit
+
+class QrScannerActivity : Activity() {
+ private lateinit var binding: ActivityOrQrScannerBinding
+
+ private var imageCapture: ImageCapture? = null
+
+ private lateinit var outputDirectory: File
+ private lateinit var cameraExecutor: ExecutorService
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ binding = ActivityOrQrScannerBinding.inflate(layoutInflater)
+ val view = binding.root
+ setContentView(view)
+
+ // Request camera permissions
+ if (allPermissionsGranted()) {
+ startCamera()
+ } else {
+ ActivityCompat.requestPermissions(
+ this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS
+ )
+ }
+
+ // Setup the listener for take photo button
+// camera_capture_button.setOnClickListener { takePhoto() }
+
+ outputDirectory = getOutputDirectory()
+
+ cameraExecutor = Executors.newSingleThreadExecutor()
+ }
+
+ private fun takePhoto() {
+ // Get a stable reference of the modifiable image capture use case
+ val imageCapture = imageCapture ?: return
+
+ // Create timestamped output file to hold the image
+ val photoFile = File(
+ outputDirectory,
+ SimpleDateFormat(
+ FILENAME_FORMAT, Locale.US
+ ).format(System.currentTimeMillis()) + ".jpg"
+ )
+
+ // Create output options object which contains file + metadata
+ val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build()
+
+ // Setup image capture listener which is triggered after photo has
+ // been taken
+ imageCapture.takePicture(
+ outputOptions,
+ ContextCompat.getMainExecutor(this),
+ object : ImageCapture.OnImageSavedCallback {
+ override fun onError(exc: ImageCaptureException) {
+ Log.e(TAG, "Photo capture failed: ${exc.message}", exc)
+ }
+
+ override fun onImageSaved(output: ImageCapture.OutputFileResults) {
+ val savedUri = Uri.fromFile(photoFile)
+ val msg = "Photo capture succeeded: $savedUri"
+ Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
+ Log.d(TAG, msg)
+ }
+ })
+ }
+
+ private fun startCamera() {
+ val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
+
+ cameraProviderFuture.addListener(Runnable {
+ // Used to bind the lifecycle of cameras to the lifecycle owner
+ val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
+
+ // Preview
+ val preview = Preview.Builder()
+ .build()
+ .also {
+ it.setSurfaceProvider(viewFinder.createSurfaceProvider())
+ }
+
+ imageCapture = ImageCapture.Builder()
+ .build()
+
+ val imageAnalyzer = ImageAnalysis.Builder()
+ .build()
+ .also {
+ it.setAnalyzer(cameraExecutor, QrAnalyzer { luma ->
+ Log.d(TAG, "Average luminosity: $luma")
+ })
+ }
+
+ // Select back camera as a default
+ val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
+
+ try {
+ // Unbind use cases before rebinding
+ cameraProvider.unbindAll()
+
+ // Bind use cases to camera
+ cameraProvider.bindToLifecycle(
+ this, cameraSelector, preview, imageCapture, imageAnalyzer
+ )
+
+ } catch (exc: Exception) {
+ Log.e(TAG, "Use case binding failed", exc)
+ }
+
+ }, ContextCompat.getMainExecutor(this))
+ }
+
+ private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all {
+ ContextCompat.checkSelfPermission(
+ baseContext, it
+ ) == PackageManager.PERMISSION_GRANTED
+ }
+
+ private fun getOutputDirectory(): File {
+ val mediaDir = externalMediaDirs.firstOrNull()?.let {
+ File(it, resources.getString(R.string.app_name)).apply { mkdirs() }
+ }
+ return if (mediaDir != null && mediaDir.exists())
+ mediaDir else filesDir
+ }
+
+ override fun onDestroy() {
+ super.onDestroy()
+ cameraExecutor.shutdown()
+ }
+
+ override fun onRequestPermissionsResult(
+ requestCode: Int, permissions: Array<String>, grantResults:
+ IntArray
+ ) {
+ if (requestCode == REQUEST_CODE_PERMISSIONS) {
+ if (allPermissionsGranted()) {
+ startCamera()
+ } else {
+ Toast.makeText(
+ this,
+ "Permissions not granted by the user.",
+ Toast.LENGTH_SHORT
+ ).show()
+ finish()
+ }
+ }
+ }
+
+ companion object {
+ private const val TAG = "CameraXBasic"
+ private const val FILENAME_FORMAT = "yyyy-MM-dd-HH-mm-ss-SSS"
+ private const val REQUEST_CODE_PERMISSIONS = 10
+ private val REQUIRED_PERMISSIONS = arrayOf(Manifest.permission.CAMERA)
+ }
+}
+
+class QrAnalyzer(private val listener: QrListener) : ImageAnalysis.Analyzer {
+
+ private fun ByteBuffer.toByteArray(): ByteArray {
+ rewind() // Rewind the buffer to zero
+ val data = ByteArray(remaining())
+ get(data) // Copy the buffer into a byte array
+ return data // Return the byte array
+ }
+
+ @SuppressLint("UnsafeExperimentalUsageError")
+ override fun analyze(image: ImageProxy) {
+
+ val mediaImage = image.image
+ if (mediaImage != null) {
+ val img = InputImage.fromMediaImage(mediaImage, image.imageInfo.rotationDegrees)
+ // Pass image to an ML Kit Vision API
+ // ...
+ scan(img)
+ }
+
+ image.close()
+ }
+
+ private fun scan(image: InputImage) {
+
+ val options = BarcodeScannerOptions.Builder()
+ .setBarcodeFormats(
+ Barcode.FORMAT_ALL_FORMATS
+ )
+ .build()
+
+ val scanner = BarcodeScanning.getClient(options)
+ val result = scanner.process(image)
+ .addOnSuccessListener { barcodes ->
+ // Task completed successfully
+ // [START_EXCLUDE]
+ // [START get_barcodes]
+ for (barcode in barcodes) {
+ val bounds = barcode.boundingBox
+ val corners = barcode.cornerPoints
+
+ val rawValue = barcode.rawValue
+
+ val valueType = barcode.valueType
+ // See API reference for complete list of supported types
+ Log.v("TESTING: ", "Barcode detected: $rawValue")
+ }
+ }
+ .addOnFailureListener { }
+ .addOnCompleteListener { }
+ }
+}
\ No newline at end of file
diff --git a/console/android/ORLib/src/main/res/layout/activity_or_qr_scanner.xml b/console/android/ORLib/src/main/res/layout/activity_or_qr_scanner.xml
new file mode 100644
index 000000000..1d7f1afa5
--- /dev/null
+++ b/console/android/ORLib/src/main/res/layout/activity_or_qr_scanner.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ xmlns:tools="http://schemas.android.com/tools"
+ tools:context=".ui.QrScannerActivity">
+
+</androidx.constraintlayout.widget.ConstraintLayout>
\ No newline at end of file