-
Notifications
You must be signed in to change notification settings - Fork 0
/
NanodetncnnActivity.kt
459 lines (391 loc) · 16.4 KB
/
NanodetncnnActivity.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
package li.garteroboter.pren.nanodet
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.PixelFormat
import android.media.Ringtone
import android.media.RingtoneManager
import android.os.Bundle
import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.view.WindowManager
import android.widget.AdapterView
import android.widget.LinearLayout
import android.widget.Spinner
import androidx.activity.viewModels
import androidx.annotation.NonNull
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.NavHostFragment
import androidx.preference.PreferenceManager
import kotlinx.coroutines.launch
import li.garteroboter.pren.Constants.STOP_COMMAND_ESP32
import li.garteroboter.pren.R
import li.garteroboter.pren.databinding.ActivityNanodetncnnBinding
import li.garteroboter.pren.preferences.bundle.CustomSettingsBundle
import li.garteroboter.pren.qrcode.fragments.GlobalStateViewModel
import li.garteroboter.pren.qrcode.fragments.IntermediateFragment
import li.garteroboter.pren.socket.SocketType
import li.garteroboter.pren.socket.WebSocketManager
import org.apache.commons.io.FileUtils
import simple.bluetooth.terminal.DevicesFragment
import simple.bluetooth.terminal.TerminalFragment
import java.io.File
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
class NanodetncnnActivity : AppCompatActivity(), SurfaceHolder.Callback, PlaySoundListener {
private val globalStateViewModel: GlobalStateViewModel by viewModels()
private var lastTimePlantCallback: Long = 0
private val atomicCounter = AtomicInteger(0)
private val nanodetncnn = NanoDetNcnn()
private var current_model = 0
private var current_cpugpu = 0
private var cameraView: SurfaceView? = null
private var ringtone: Ringtone? = null
private var terminalFragment: TerminalFragment? = null
private var currentSurfaceViewWidth = 0
private var currentSurfaceViewHeight = 0
// Initialization by lazy { ... } is thread-safe by default
private val manager: WebSocketManager? by lazy {
WebSocketManager(this@NanodetncnnActivity, HOSTNAME).apply {
lifecycleScope.launch {
createAndOpenWebSocketConnection(SocketType.Binary)
}
}
}
private lateinit var binding: ActivityNanodetncnnBinding
// preferences
private var useBluetooth = false
private var numerOfConfirmations = 3 // accept Plant detection result aftter N confirmations
private val waitingTimePlantCallback = 5000 // to configure the bluetooth calls
private var plantCount = -1
private var switchQr = true
private var prob_threshhold = -1f
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityNanodetncnnBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
val settingsBundle = generatePreferenceBundle()
useBluetooth = settingsBundle.isUsingBluetooth
numerOfConfirmations = settingsBundle.confirmations
plantCount = settingsBundle.plantCount
switchQr = settingsBundle.isSwitchToQr
prob_threshhold = settingsBundle.prob_threshold
setupFragmentBluetoothChain()
observeViewModels()
injectPreferences(settingsBundle)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
cameraView = binding.cameraview
cameraView!!.holder.setFormat(PixelFormat.RGBA_8888)
cameraView!!.holder.addCallback(this)
setupSpinnerOnClick(binding.spinnerModel)
setupSpinnerCPUGPUOnClick(binding.spinnerCPUGPU)
binding.mainButtonSwitchCameraSource.setOnClickListener { navigateCameraFragment() }
val notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
ringtone = RingtoneManager.getRingtone(applicationContext, notification)
setupAtomicCounterInterval()
reload()
}
private fun observeViewModels() {
globalStateViewModel.getCurrentDriveState().observe(this, Observer { state ->
Log.i(TAG, "viewModel.getCurrentState().observe")
reOpenNanodetCamera()
})
globalStateViewModel.getCurrentImage().observe(this, Observer { image ->
Log.i(TAG, "viewModel.getCurrentImage().observe")
uploadPlantFromFile(image)
})
}
private fun uploadPlantFromFile(file: File?) {
Log.i(TAG,"uploadPlantFromFile" )
file?.let { it ->
try {
val bytes = FileUtils.readFileToByteArray(it)
manager?.sendBytes(bytes) ?: Log.e(TAG, "manager == null")
} catch (e: Exception) {
e.printStackTrace()
}
}
}
private fun injectPreferences(settingsBundle: CustomSettingsBundle) {
// creates a reference to the currently active instance
// of MainActivityNanodetNCNN in the C++ layer
nanodetncnn.setObjectReferenceAsGlobal(this)
nanodetncnn.injectBluetoothSettings(settingsBundle.isUsingBluetooth)
nanodetncnn.injectFPSPreferences(settingsBundle.isShowFPS)
nanodetncnn.injectProbThresholdSettings(settingsBundle.prob_threshold)
}
private fun setupFragmentBluetoothChain() {
val devicesFragment = DevicesFragment.newInstance()
val autoConnectBluetooth = setupBluetoothPermission()
devicesFragment.arguments = autoConnectBluetooth
supportFragmentManager.beginTransaction().add(
R.id.fragmentBluetoothChain,
devicesFragment, "devices"
).commit()
}
override fun onRequestPermissionsResult(
requestCode: Int,
@NonNull permissions: Array<String>,
@NonNull grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == REQUEST_PERMISSIONS_CODE_BLUETOOTH_CONNECT) {
val args = Bundle()
args.putString("autoConnect", "true")
val devicesFragment = DevicesFragment.newInstance()
devicesFragment.arguments = args
supportFragmentManager.beginTransaction().add(
R.id.fragmentBluetoothChain,
devicesFragment, "devices"
).commit()
}
}
private fun setupBluetoothPermission(): Bundle {
val args = Bundle()
if (useBluetooth) {
if (ActivityCompat.checkSelfPermission(
applicationContext,
Manifest.permission.BLUETOOTH_CONNECT
)
!= PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.BLUETOOTH_CONNECT),
REQUEST_PERMISSIONS_CODE_BLUETOOTH_CONNECT
)
} else {
args.putString("autoConnect", "true")
}
} else {
args.putString("autoConnect", "false")
}
return args
}
private fun reload() {
val retryInit = nanodetncnn.loadModel(assets, current_model, current_cpugpu)
if (!retryInit) {
Log.e("MainActivity", "nanodetncnn loadModel failed")
}
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
nanodetncnn.setOutputWindow(holder.surface)
}
override fun surfaceCreated(holder: SurfaceHolder) {}
override fun surfaceDestroyed(holder: SurfaceHolder) {}
/** This method is called by the native layer.
* It is in a sense the most important part of this application.
* Note that this is effectively called by a different thread.
* It _is_ a different thread. that also means you cannot change the UI from this method directly */
fun plantVaseDetectedCallback(objectLabel: String?, probability: String?) {
val _count = atomicCounter.incrementAndGet()
if (_count != 0) {
// Log.v(TAG,String.format("current number of confirmations = %d", _count))
}
if (_count >= numerOfConfirmations) { // count = number of confirmations. The lower, the faster
atomicCounter.set(0) // reset the counter back
if (lastTimeWasNSecondsAGo()) {
lastTimePlantCallback = System.currentTimeMillis()
Log.d(
TAG,
String.format("Accept potted plant detection with %d confirmations", _count)
)
synchronized(this) {
if (bluetoothCheck(terminalFragment)) {
terminalFragment!!.send(STOP_COMMAND_ESP32)
}
}
startRingtone()
runOnUiThread(Runnable {
if (switchQr) {
navigateCameraFragment()
}
updateDescription(
"detected %s, latest probability == %s".format(
objectLabel,
probability
)
)
})
}
}
}
private fun lastTimeWasNSecondsAGo(): Boolean {
return System.currentTimeMillis() - lastTimePlantCallback > waitingTimePlantCallback
}
private fun bluetoothCheck(terminalFragment: TerminalFragment?): Boolean {
if (useBluetooth && terminalFragment != null) {
return true
}
if (terminalFragment == null) {
Log.d(TAG, "bluetoothCheck failed, terminalFragment == null ")
}
return false
}
private fun updateDescription(text: String) {
binding.textViewDetectedObjectLabel.text = text
}
private fun setupAtomicCounterInterval() {
// To be absolutely certain we have a plant detected, and not a false positive, I
// implemented a little extra check.
// It will watch for a fast burst of plantVaseDetectedCallback.
// To detect that burst of callbacks in a short period of time, I use an atomicCounter.
// This atomicCounter tracks the number of plantVaseDetectedCallback in a given interval.
// After the interval has passed, simply reset the atomicCounter back to zero.
val resetAtomicCounterEveryNSeconds = Runnable {
Log.v(TAG, "resetting counter")
atomicCounter.incrementAndGet()
}
val executor = Executors.newScheduledThreadPool(1)
executor.scheduleAtFixedRate(
resetAtomicCounterEveryNSeconds, 0, 3, TimeUnit.SECONDS
)
}
private fun navigateCameraFragment() {
nanodetncnn.closeCamera()
shrinkSufaceView()
// TODO: the following block is probably not optional.
// It may be better to make use of shared viewmodel aswell,
val navHostFragment = binding.fragmentContainer.getFragment<NavHostFragment>()
val fragment: Fragment = navHostFragment.childFragmentManager.fragments[0]
val intermediateFragment = fragment as IntermediateFragment
intermediateFragment.navigateToCamera()
}
/** This is a little trick I use so that the CameraFragment gets displayed. */
private fun shrinkSufaceView() {
currentSurfaceViewWidth = cameraView!!.layoutParams.width // save to restore later
currentSurfaceViewHeight = cameraView!!.layoutParams.height
cameraView!!.layoutParams =
LinearLayout.LayoutParams(currentSurfaceViewWidth, 1) // shrink
}
private fun reOpenNanodetCamera() {
Log.i(TAG, "reOpenNanodetCamera")
unShrinkSufaceView()
nanodetncnn.openCamera(CAMERA_ORIENTATION)
}
private fun unShrinkSufaceView() {
cameraView!!.layoutParams.width = currentSurfaceViewWidth
cameraView!!.layoutParams.height = currentSurfaceViewHeight
cameraView!!.layoutParams =
LinearLayout.LayoutParams(currentSurfaceViewWidth, currentSurfaceViewHeight)
}
/** Called from terminal Fragment */
fun receiveTerminalFragmentReference(terminalFragment: TerminalFragment?) {
if (bluetoothCheck(terminalFragment)) {
this.terminalFragment = terminalFragment
} else {
Log.e(
TAG,
"receiveTerminalFragmentReference failed to get reference to terminalFragment"
)
}
}
public override fun onResume() {
super.onResume()
if (ContextCompat.checkSelfPermission(
applicationContext,
Manifest.permission.CAMERA
) == PackageManager.PERMISSION_DENIED
) {
ActivityCompat.requestPermissions(
this, arrayOf(Manifest.permission.CAMERA),
REQUEST_CAMERA
)
}
nanodetncnn.openCamera(CAMERA_ORIENTATION)
}
override fun startRingtone() {
if (TOGGLE_RINGTONE) {
try {
ringtone!!.play()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
private fun setupSpinnerCPUGPUOnClick(spinnerCPUGPU: Spinner) {
spinnerCPUGPU.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
arg0: AdapterView<*>?,
arg1: View,
position: Int,
id: Long
) {
if (position != current_cpugpu) {
current_cpugpu = position
reload()
}
}
override fun onNothingSelected(arg0: AdapterView<*>?) {}
}
}
private fun setupSpinnerOnClick(spinnerModel: Spinner) {
spinnerModel.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
arg0: AdapterView<*>?,
arg1: View,
position: Int,
id: Long
) {
if (position != current_model) {
current_model = position
reload()
}
}
override fun onNothingSelected(arg0: AdapterView<*>?) {}
}
}
// creates an object, which is a container for some preferences. This bundle object is then
// passed to the native layer)
private fun generatePreferenceBundle(): CustomSettingsBundle {
val preferences = PreferenceManager.getDefaultSharedPreferences(
applicationContext
)
val useBluetooth = preferences.getBoolean("key_bluetooth", false)
val drawFps = preferences.getBoolean("key_fps", false)
val _value = preferences.getString("key_prob_threshold", "0.40")
val probThreshold = _value!!.toFloat()
val plantCount = preferences.getInt("number_picker_preference", 6)
val switchToQr = preferences.getBoolean("key_start_transition", true)
val _confirmations = preferences.getString("confirmation_number_picker", "3")
val confirmations = _confirmations!!.toInt()
return CustomSettingsBundle(
useBluetooth,
drawFps,
probThreshold,
switchToQr,
confirmations,
plantCount
)
}
public override fun onPause() {
super.onPause()
nanodetncnn.closeCamera()
}
companion object {
const val REQUEST_CAMERA = 100
const val CAMERA_ORIENTATION = 1
private const val TAG = "MainActivityNanodetNCNN"
private const val HOSTNAME = "wss://pren.garteroboter.li:443/ws/";
var TOGGLE_RINGTONE = true
private const val REQUEST_PERMISSIONS_CODE_BLUETOOTH_CONNECT = 11
/** Use external media if it is available, our app's file directory otherwise */
fun getOutputDirectory(context: Context): File {
val appContext = context.applicationContext
val mediaDir = context.externalMediaDirs.firstOrNull()?.let {
File(it, appContext.resources.getString(R.string.app_name)).apply { mkdirs() }
}
return if (mediaDir != null && mediaDir.exists())
mediaDir else appContext.filesDir
}
}
}