-
Notifications
You must be signed in to change notification settings - Fork 510
/
CameraActivity.java
executable file
·1468 lines (1306 loc) · 50.1 KB
/
CameraActivity.java
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Modified by Matthias Mueller - Intel Intelligent Systems Lab - 2020
package org.openbot.original;
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.Image.Plane;
import android.media.ImageReader;
import android.media.ImageReader.OnImageAvailableListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.os.SystemClock;
import android.os.Trace;
import android.util.Log;
import android.util.Size;
import android.view.Surface;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import java.io.File;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.json.JSONObject;
import org.openbot.OpenBotApplication;
import org.openbot.R;
import org.openbot.env.AudioPlayer;
import org.openbot.env.BotToControllerEventBus;
import org.openbot.env.ControllerToBotEventBus;
import org.openbot.env.GameController;
import org.openbot.env.ImageUtils;
import org.openbot.env.Logger;
import org.openbot.env.PhoneController;
import org.openbot.env.SharedPreferencesManager;
import org.openbot.logging.LogDataUtils;
import org.openbot.logging.SensorService;
import org.openbot.server.ServerCommunication;
import org.openbot.server.ServerListener;
import org.openbot.tflite.Model;
import org.openbot.tflite.Network.Device;
import org.openbot.utils.ConnectionUtils;
import org.openbot.utils.Constants;
import org.openbot.utils.Enums;
import org.openbot.utils.Enums.ControlMode;
import org.openbot.utils.Enums.DriveMode;
import org.openbot.utils.Enums.LogMode;
import org.openbot.utils.Enums.SpeedMode;
import org.openbot.utils.FileUtils;
import org.openbot.utils.FormatUtils;
import org.openbot.utils.PermissionUtils;
import org.openbot.vehicle.Control;
import org.openbot.vehicle.Vehicle;
import org.zeroturnaround.zip.ZipUtil;
import timber.log.Timber;
public abstract class CameraActivity extends AppCompatActivity
implements OnImageAvailableListener,
Camera.PreviewCallback,
CompoundButton.OnCheckedChangeListener,
ServerListener,
View.OnClickListener,
AdapterView.OnItemSelectedListener {
private static final Logger LOGGER = new Logger();
private static final String TAG = "CameraActivity";
private static Context context;
private int cameraSelection = CameraCharacteristics.LENS_FACING_BACK;
protected int previewWidth = 0;
protected int previewHeight = 0;
private final boolean debug = false;
private Handler handler;
private HandlerThread handlerThread;
private boolean useCamera2API;
private boolean isProcessingFrame = false;
private final byte[][] yuvBytes = new byte[3][];
private int[] rgbBytes = null;
private int yRowStride;
private Runnable postInferenceCallback;
private Runnable imageConverter;
private LinearLayout bottomSheetLayout;
private LinearLayout gestureLayout;
private BottomSheetBehavior sheetBehavior;
protected SwitchCompat connectionSwitchCompat,
networkSwitchCompat,
logSwitchCompat,
cameraSwitchCompat;
protected TextView frameValueTextView,
cropValueTextView,
inferenceTimeTextView,
controlValueTextView;
protected ImageView bottomSheetArrowImageView;
private ImageView plusImageView, minusImageView;
protected Spinner baudRateSpinner,
modelSpinner,
deviceSpinner,
controlModeSpinner,
driveModeSpinner,
logSpinner,
speedModeSpinner;
private TextView threadsTextView, voltageTextView, speedTextView, sonarTextView;
private ArrayAdapter<CharSequence> modelAdapter;
private List<Model> masterList;
private Model model;
private Device device = Device.CPU;
private int numThreads = -1;
public int[] BaudRates = {9600, 14400, 19200, 38400, 57600, 115200, 230400, 460800, 921600};
private int baudRate = 115200;
private LocalBroadcastManager localBroadcastManager;
private BroadcastReceiver localBroadcastReceiver;
protected LogMode logMode = LogMode.CROP_IMG;
protected ControlMode controlMode = ControlMode.GAMEPAD;
protected SpeedMode speedMode = SpeedMode.NORMAL;
protected DriveMode driveMode = DriveMode.GAME;
protected String logFolder;
protected boolean loggingEnabled;
protected boolean networkEnabled = false;
protected boolean noiseEnabled = false;
private Intent intentSensorService;
private ServerCommunication serverCommunication;
private SharedPreferencesManager preferencesManager;
protected final GameController gameController = new GameController(driveMode);
private PhoneController phoneController;
protected final ControllerHandler controllerHandler = new ControllerHandler();
private final AudioPlayer audioPlayer = new AudioPlayer(this);
private final String voice = "matthew";
protected Vehicle vehicle;
@Override
protected void onCreate(final Bundle savedInstanceState) {
LOGGER.d("onCreate " + this);
super.onCreate(null);
context = getApplicationContext();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
vehicle = OpenBotApplication.vehicle;
phoneController = PhoneController.getInstance(this);
setContentView(R.layout.activity_camera);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
if (PermissionUtils.hasCameraPermission(this)) {
setFragment();
} else {
PermissionUtils.requestCameraPermission(this);
}
preferencesManager = new SharedPreferencesManager(this);
connectionSwitchCompat = findViewById(R.id.connection_switch);
threadsTextView = findViewById(R.id.threads);
plusImageView = findViewById(R.id.plus);
minusImageView = findViewById(R.id.minus);
networkSwitchCompat = findViewById(R.id.network_switch);
bottomSheetLayout = findViewById(R.id.bottom_sheet_layout);
gestureLayout = findViewById(R.id.gesture_layout);
sheetBehavior = BottomSheetBehavior.from(bottomSheetLayout);
bottomSheetArrowImageView = findViewById(R.id.bottom_sheet_arrow);
logSwitchCompat = findViewById(R.id.logger_switch);
cameraSwitchCompat = findViewById(R.id.camera_toggle_switch);
baudRateSpinner = findViewById(R.id.baud_rate_spinner);
ArrayAdapter<CharSequence> baudRateAdapter =
ArrayAdapter.createFromResource(this, R.array.baud_rates, R.layout.spinner_item);
baudRateAdapter.setDropDownViewResource(android.R.layout.simple_list_item_checked);
baudRateSpinner.setAdapter(baudRateAdapter);
modelSpinner = findViewById(R.id.model_spinner);
masterList = FileUtils.loadConfigJSONFromAsset(this);
List<String> models =
masterList.stream()
.filter(f -> f.pathType != Model.PATH_TYPE.URL)
.map(f -> FileUtils.nameWithoutExtension(f.name))
.collect(Collectors.toList());
masterList.stream()
.filter(f -> f.name.contains(preferencesManager.getDefaultModel()))
.findFirst()
.ifPresent(f -> model = f);
modelAdapter = new ArrayAdapter<>(this, R.layout.spinner_item, new ArrayList<>(models));
modelAdapter.setDropDownViewResource(android.R.layout.simple_list_item_checked);
modelSpinner.setAdapter(modelAdapter);
deviceSpinner = findViewById(R.id.device_spinner);
ArrayAdapter<CharSequence> deviceAdapter =
ArrayAdapter.createFromResource(this, R.array.devices, R.layout.spinner_item);
deviceAdapter.setDropDownViewResource(android.R.layout.simple_list_item_checked);
deviceSpinner.setAdapter(deviceAdapter);
logSpinner = findViewById(R.id.log_spinner);
ArrayAdapter<CharSequence> logAdapter =
ArrayAdapter.createFromResource(this, R.array.log_settings, R.layout.spinner_item);
logAdapter.setDropDownViewResource(android.R.layout.simple_list_item_checked);
logSpinner.setAdapter(logAdapter);
controlModeSpinner = findViewById(R.id.control_mode_spinner);
ArrayAdapter<CharSequence> controlModeAdapter =
ArrayAdapter.createFromResource(this, R.array.control_modes, R.layout.spinner_item);
controlModeAdapter.setDropDownViewResource(android.R.layout.simple_list_item_checked);
controlModeSpinner.setAdapter(controlModeAdapter);
driveModeSpinner = findViewById(R.id.drive_mode_spinner);
ArrayAdapter<CharSequence> driveModeAdapter =
ArrayAdapter.createFromResource(this, R.array.drive_modes, R.layout.spinner_item);
driveModeAdapter.setDropDownViewResource(android.R.layout.simple_list_item_checked);
driveModeSpinner.setAdapter(driveModeAdapter);
speedModeSpinner = findViewById(R.id.speed_mode_spinner);
ArrayAdapter<CharSequence> controlAdapter =
ArrayAdapter.createFromResource(this, R.array.speed_modes, R.layout.spinner_item);
controlAdapter.setDropDownViewResource(android.R.layout.simple_list_item_checked);
speedModeSpinner.setAdapter(controlAdapter);
ViewTreeObserver vto = gestureLayout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
gestureLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
// int width = bottomSheetLayout.getMeasuredWidth();
int height = gestureLayout.getMeasuredHeight();
sheetBehavior.setPeekHeight(height);
}
});
sheetBehavior.setHideable(false);
sheetBehavior.setBottomSheetCallback(
new BottomSheetBehavior.BottomSheetCallback() {
@Override
public void onStateChanged(@NonNull View bottomSheet, int newState) {
switch (newState) {
case BottomSheetBehavior.STATE_HIDDEN:
break;
case BottomSheetBehavior.STATE_EXPANDED:
bottomSheetArrowImageView.setImageResource(R.drawable.icn_chevron_down);
preferencesManager.setSheetExpanded(true);
break;
case BottomSheetBehavior.STATE_COLLAPSED:
bottomSheetArrowImageView.setImageResource(R.drawable.icn_chevron_up);
preferencesManager.setSheetExpanded(false);
break;
case BottomSheetBehavior.STATE_DRAGGING:
break;
case BottomSheetBehavior.STATE_SETTLING:
bottomSheetArrowImageView.setImageResource(R.drawable.icn_chevron_up);
break;
}
}
@Override
public void onSlide(@NonNull View bottomSheet, float slideOffset) {}
});
voltageTextView = findViewById(R.id.voltage_info);
speedTextView = findViewById(R.id.speed_info);
sonarTextView = findViewById(R.id.sonar_info);
frameValueTextView = findViewById(R.id.frame_info);
cropValueTextView = findViewById(R.id.crop_info);
inferenceTimeTextView = findViewById(R.id.inference_info);
controlValueTextView = findViewById(R.id.control_info);
connectionSwitchCompat.setOnCheckedChangeListener(this);
networkSwitchCompat.setOnCheckedChangeListener(this);
logSwitchCompat.setOnCheckedChangeListener(this);
cameraSwitchCompat.setOnCheckedChangeListener(this);
plusImageView.setOnClickListener(this);
minusImageView.setOnClickListener(this);
baudRateSpinner.setOnItemSelectedListener(this);
modelSpinner.setOnItemSelectedListener(this);
deviceSpinner.setOnItemSelectedListener(this);
logSpinner.setOnItemSelectedListener(this);
controlModeSpinner.setOnItemSelectedListener(this);
driveModeSpinner.setOnItemSelectedListener(this);
speedModeSpinner.setOnItemSelectedListener(this);
// Intent for sensor service
intentSensorService = new Intent(this, SensorService.class);
setInitialValues();
// Try to connect to serial device
toggleConnection(true);
localBroadcastReceiver =
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action != null) {
switch (action) {
case Constants.USB_ACTION_DATA_RECEIVED:
long timestamp = SystemClock.elapsedRealtimeNanos();
String data = intent.getStringExtra("data");
char header = data.charAt(0);
String body = data.substring(1);
int type = -1;
switch (header) {
case 'f':
vehicle.processVehicleConfig(body);
break;
case 'v':
if (FormatUtils.isNumeric(body)) {
type = SensorService.MSG_VOLTAGE;
vehicle.setBatteryVoltage(Float.parseFloat(body));
runOnUiThread(
() -> {
voltageTextView.setText(
String.format(Locale.US, "%2.1f V", vehicle.getBatteryVoltage()));
});
} else {
String[] msgParts = body.split(":");
switch (msgParts[0]) {
case "min":
vehicle.setMinMotorVoltage(Float.parseFloat(msgParts[1]));
break;
case "low":
vehicle.setLowBatteryVoltage(Float.parseFloat(msgParts[1]));
break;
case "max":
vehicle.setMaxBatteryVoltage(Float.parseFloat(msgParts[1]));
break;
default:
Toast.makeText(
getApplicationContext(),
"Invalid voltage message received!",
Toast.LENGTH_SHORT)
.show();
break;
}
}
break;
case 's':
if (FormatUtils.isNumeric(body)) {
type = SensorService.MSG_SONAR;
vehicle.setSonarReading(Float.parseFloat(body));
runOnUiThread(
() -> {
sonarTextView.setText(
String.format(Locale.US, "%3.0f cm", vehicle.getSonarReading()));
});
}
break;
case 'w':
String[] itemList = body.split(",");
if (itemList.length == 2
&& FormatUtils.isNumeric(itemList[0])
&& FormatUtils.isNumeric(itemList[1])) {
type = SensorService.MSG_WHEELS;
vehicle.setLeftWheelRpm(Float.parseFloat(itemList[0]));
vehicle.setRightWheelRpm(Float.parseFloat(itemList[1]));
runOnUiThread(
() -> {
speedTextView.setText(
String.format(
Locale.US,
"%3.0f,%3.0f rpm",
vehicle.getLeftWheelRpm(),
vehicle.getRightWheelRpm()));
});
}
break;
case 'b':
type = SensorService.MSG_BUMPER;
break;
}
if (type > 0) sendVehicleDataToSensorService(timestamp, data, type);
break;
}
}
}
};
IntentFilter localIntentFilter = new IntentFilter();
localIntentFilter.addAction(Constants.USB_ACTION_DATA_RECEIVED);
localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.registerReceiver(localBroadcastReceiver, localIntentFilter);
vehicle.requestVehicleConfig();
}
@SuppressLint("SetTextI18n")
private void setInitialValues() {
cameraSwitchCompat.setChecked(preferencesManager.getCameraSwitch());
baudRateSpinner.setSelection(Arrays.binarySearch(BaudRates, preferencesManager.getBaudrate()));
if (!preferencesManager.getDefaultModel().isEmpty())
modelSpinner.setSelection(
Math.max(
0,
modelAdapter.getPosition(
FileUtils.nameWithoutExtension(preferencesManager.getDefaultModel()))));
deviceSpinner.setSelection(preferencesManager.getDevice());
logSpinner.setSelection(preferencesManager.getLogMode());
if (ControlMode.getByID(preferencesManager.getControlMode()) != null)
controlModeSpinner.setSelection(
Objects.requireNonNull(ControlMode.getByID(preferencesManager.getControlMode()))
.ordinal());
if (DriveMode.getByID(preferencesManager.getDriveMode()) != null)
driveModeSpinner.setSelection(
Objects.requireNonNull(DriveMode.getByID(preferencesManager.getDriveMode())).ordinal());
if (SpeedMode.getByID(preferencesManager.getSpeedMode()) != null)
speedModeSpinner.setSelection(
Objects.requireNonNull(SpeedMode.getByID(preferencesManager.getSpeedMode())).ordinal());
setNumThreads(preferencesManager.getNumThreads());
threadsTextView.setText(Integer.toString(numThreads));
if (preferencesManager.getSheetExpanded()) {
sheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
}
}
protected int[] getRgbBytes() {
imageConverter.run();
return rgbBytes;
}
protected int getLuminanceStride() {
return yRowStride;
}
protected byte[] getLuminance() {
return yuvBytes[0];
}
/** Callback for android.hardware.Camera API */
@Override
public void onPreviewFrame(final byte[] bytes, final Camera camera) {
if (isProcessingFrame) {
LOGGER.w("Dropping frame!");
return;
}
try {
// Initialize the storage bitmaps once when the resolution is known.
if (rgbBytes == null) {
Camera.Size previewSize = camera.getParameters().getPreviewSize();
previewHeight = previewSize.height;
previewWidth = previewSize.width;
rgbBytes = new int[previewWidth * previewHeight];
onPreviewSizeChosen(new Size(previewSize.width, previewSize.height), 90);
}
} catch (final Exception e) {
LOGGER.e(e, "Exception!");
return;
}
isProcessingFrame = true;
yuvBytes[0] = bytes;
yRowStride = previewWidth;
imageConverter =
new Runnable() {
@Override
public void run() {
ImageUtils.convertYUV420SPToARGB8888(bytes, previewWidth, previewHeight, rgbBytes);
}
};
postInferenceCallback =
new Runnable() {
@Override
public void run() {
camera.addCallbackBuffer(bytes);
isProcessingFrame = false;
}
};
processImage();
}
/** Callback for Camera2 API */
@Override
public void onImageAvailable(final ImageReader reader) {
// We need wait until we have some size from onPreviewSizeChosen
if (previewWidth == 0 || previewHeight == 0) {
return;
}
if (rgbBytes == null) {
rgbBytes = new int[previewWidth * previewHeight];
}
try {
final Image image = reader.acquireLatestImage();
if (image == null) {
return;
}
if (isProcessingFrame) {
image.close();
return;
}
isProcessingFrame = true;
Trace.beginSection("imageAvailable");
final Plane[] planes = image.getPlanes();
fillBytes(planes, yuvBytes);
yRowStride = planes[0].getRowStride();
final int uvRowStride = planes[1].getRowStride();
final int uvPixelStride = planes[1].getPixelStride();
imageConverter =
new Runnable() {
@Override
public void run() {
ImageUtils.convertYUV420ToARGB8888(
yuvBytes[0],
yuvBytes[1],
yuvBytes[2],
previewWidth,
previewHeight,
yRowStride,
uvRowStride,
uvPixelStride,
rgbBytes);
}
};
postInferenceCallback =
new Runnable() {
@Override
public void run() {
image.close();
isProcessingFrame = false;
}
};
processImage();
} catch (final Exception e) {
LOGGER.e(e, "Exception!");
Trace.endSection();
return;
}
Trace.endSection();
}
@Override
public synchronized void onStart() {
LOGGER.d("onStart " + this);
super.onStart();
}
@Override
public synchronized void onResume() {
LOGGER.d("onResume " + this);
super.onResume();
handlerThread = new HandlerThread("inference");
handlerThread.start();
handler = new Handler(handlerThread.getLooper());
serverCommunication = new ServerCommunication(this, this);
serverCommunication.start();
}
@Override
public void onAddModel(String model) {
Model item =
new Model(
masterList.size() + 1,
Model.CLASS.AUTOPILOT_F,
Model.TYPE.AUTOPILOT,
model,
Model.PATH_TYPE.FILE,
getFilesDir() + File.separator + model,
"256x96");
if (modelAdapter != null && modelAdapter.getPosition(model) == -1) {
modelAdapter.add(model);
masterList.add(item);
FileUtils.updateModelConfig(this, masterList);
} else {
if (model.equals(modelSpinner.getSelectedItem())) {
setModel(item);
}
}
Toast.makeText(context, "AutopilotModel added: " + model, Toast.LENGTH_SHORT).show();
}
@Override
public void onRemoveModel(String model) {
if (modelAdapter != null && modelAdapter.getPosition(model) != -1) {
modelAdapter.remove(model);
}
Toast.makeText(context, "AutopilotModel removed: " + model, Toast.LENGTH_SHORT).show();
}
@Override
public void onServerListChange(Set<String> servers) {}
@Override
public void onConnectionEstablished(String ipAddress) {}
@Override
public synchronized void onPause() {
LOGGER.d("onPause " + this);
handlerThread.quitSafely();
try {
handlerThread.join();
handlerThread = null;
handler = null;
serverCommunication.stop();
} catch (final InterruptedException e) {
LOGGER.e(e, "Exception!");
}
phoneController.disconnect();
vehicle.setControl(0, 0);
super.onPause();
}
@Override
public synchronized void onStop() {
LOGGER.d("onStop " + this);
super.onStop();
}
@Override
public synchronized void onDestroy() {
// toggleConnection(false);
if (localBroadcastManager != null) {
localBroadcastManager.unregisterReceiver(localBroadcastReceiver);
localBroadcastManager = null;
}
if (localBroadcastReceiver != null) localBroadcastReceiver = null;
LOGGER.d("onDestroy " + this);
ControllerToBotEventBus.unsubscribe(this.getClass().getSimpleName());
vehicle.setControl(0, 0);
super.onDestroy();
}
protected synchronized void runInBackground(final Runnable r) {
if (handler != null) {
handler.post(r);
}
}
@Override
public void onRequestPermissionsResult(
final int requestCode, final String[] permissions, final int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case Constants.REQUEST_CAMERA_PERMISSION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
setFragment();
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(
this, Constants.PERMISSION_CAMERA)) {
Toast.makeText(
this.getApplicationContext(),
getResources().getString(R.string.camera_permission_denied)
+ " "
+ getResources().getString(R.string.permission_reason_ai),
Toast.LENGTH_LONG)
.show();
}
}
break;
case Constants.REQUEST_LOGGING_PERMISSIONS:
// If the permission is granted, start logging,
// otherwise, show a Toast
if (PermissionUtils.checkLoggingPermissions(grantResults)) setIsLoggingActive(true);
else PermissionUtils.showLoggingPermissionsToast(this);
break;
case Constants.REQUEST_CONTROLLER_PERMISSIONS:
// If the permission is granted, start advertising to controller,
// otherwise, show a Toast
if (PermissionUtils.checkControllerPermissions(grantResults)) phoneController.connect(this);
else PermissionUtils.showControllerPermissionsToast(this);
break;
}
}
// Returns true if the device supports the required hardware level, or better.
private boolean isHardwareLevelSupported(
CameraCharacteristics characteristics, int requiredLevel) {
int deviceLevel = characteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL);
if (deviceLevel == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY) {
return requiredLevel == deviceLevel;
}
// deviceLevel is not LEGACY, can use numerical sort
return requiredLevel <= deviceLevel;
}
private String chooseCamera(int facingSelection) {
final CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
for (final String cameraId : manager.getCameraIdList()) {
final CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
LOGGER.i(
"CAMERA ID: "
+ cameraId
+ " FACING: "
+ characteristics.get(CameraCharacteristics.LENS_FACING));
// We don't use a front facing camera in this sample.
final Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
if (facing != null && facing != facingSelection) {
continue;
}
final StreamConfigurationMap map =
characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if (map == null) {
continue;
}
// Fallback to camera1 API for internal cameras that don't have full support.
// This should help with legacy situations where using the camera2 API causes
// distorted or otherwise broken previews.
useCamera2API =
(facing == CameraCharacteristics.LENS_FACING_EXTERNAL)
|| isHardwareLevelSupported(
characteristics, CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL)
|| isHardwareLevelSupported(
characteristics, CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED);
LOGGER.i("Camera API lv2?: %s", useCamera2API);
return cameraId;
}
} catch (CameraAccessException e) {
LOGGER.e(e, "Not allowed to access camera");
}
return null;
}
protected void setFragment() {
cameraSelection = getCameraUserSelection();
String cameraId = chooseCamera(cameraSelection);
Fragment fragment;
if (useCamera2API) {
CameraConnectionFragment camera2Fragment =
CameraConnectionFragment.newInstance(
(size, rotation) -> {
previewHeight = size.getHeight();
previewWidth = size.getWidth();
CameraActivity.this.onPreviewSizeChosen(size, rotation);
},
this,
getLayoutId(),
getDesiredPreviewFrameSize());
camera2Fragment.setCamera(cameraId);
fragment = camera2Fragment;
} else {
fragment =
new LegacyCameraConnectionFragment(
this, getLayoutId(), getDesiredPreviewFrameSize(), cameraSelection);
}
getFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
}
protected void fillBytes(final Plane[] planes, final byte[][] yuvBytes) {
// Because of the variable row stride it's not possible to know in
// advance the actual necessary dimensions of the yuv planes.
for (int i = 0; i < planes.length; ++i) {
final ByteBuffer buffer = planes[i].getBuffer();
if (yuvBytes[i] == null) {
LOGGER.d("Initializing buffer %d at size %d", i, buffer.capacity());
yuvBytes[i] = new byte[buffer.capacity()];
}
buffer.get(yuvBytes[i]);
}
}
public boolean isDebug() {
return debug;
}
protected void readyForNextImage() {
if (postInferenceCallback != null) {
postInferenceCallback.run();
}
}
protected int getScreenOrientation() {
switch (getWindowManager().getDefaultDisplay().getRotation()) {
case Surface.ROTATION_270:
return 270;
case Surface.ROTATION_180:
return 180;
case Surface.ROTATION_90:
return 90;
default:
return 0;
}
}
protected int getCameraUserSelection() {
// during initialisation there is no cameraToggle so we assume default
if (this.cameraSwitchCompat == null) {
this.cameraSelection = CameraCharacteristics.LENS_FACING_BACK;
} else {
this.cameraSelection = this.cameraSwitchCompat.isChecked() ? 0 : 1;
}
return this.cameraSelection;
}
protected void setCameraSwitchText() {
if (this.cameraSelection == CameraCharacteristics.LENS_FACING_BACK) {
cameraSwitchCompat.setText(R.string.camera_facing_back);
} else {
cameraSwitchCompat.setText(R.string.camera_facing_front);
}
}
protected int getBaudRate() {
return baudRate;
}
private void setBaudRate(int baudRate) {
if (this.baudRate != baudRate) {
LOGGER.d("Updating baudRate: " + baudRate);
this.baudRate = baudRate;
preferencesManager.setBaudrate(baudRate);
}
}
private void setLogMode(LogMode logMode) {
if (this.logMode != logMode) {
LOGGER.d("Updating logMode: " + logMode);
this.logMode = logMode;
preferencesManager.setLogMode(logMode.ordinal());
}
}
private void setSpeedMode(SpeedMode speedMode) {
if (this.speedMode != speedMode) {
LOGGER.d("Updating speedMode: " + speedMode);
this.speedMode = speedMode;
preferencesManager.setSpeedMode(speedMode.getValue());
speedModeSpinner.setSelection(speedMode.ordinal());
vehicle.setSpeedMultiplier(speedMode.getValue());
}
}
private void setControlMode(ControlMode controlMode) {
if (this.controlMode != controlMode) {
LOGGER.d("Updating controlMode: " + controlMode);
this.controlMode = controlMode;
switch (controlMode) {
case GAMEPAD:
disconnectPhoneController();
break;
case PHONE:
handleControllerEvents();
if (!PermissionUtils.hasControllerPermissions(this)) {
PermissionUtils.requestControllerPermissions(this);
} else connectPhoneController();
break;
case WEBRTC:
break;
default:
throw new IllegalStateException("Unexpected value: " + controlMode);
}
preferencesManager.setControlMode(controlMode.getValue());
controlModeSpinner.setSelection(controlMode.ordinal());
}
}
private void connectPhoneController() {
phoneController.connect(this);
DriveMode oldDriveMode = driveMode;
// Currently only dual drive mode supported
setDriveMode(DriveMode.DUAL);
driveModeSpinner.setAlpha(0.5f);
preferencesManager.setDriveMode(oldDriveMode.getValue());
}
private void disconnectPhoneController() {
phoneController.disconnect();
setDriveMode(DriveMode.values()[preferencesManager.getDriveMode()]);
driveModeSpinner.setEnabled(true);
driveModeSpinner.setAlpha(1.0f);
}
protected void setDriveMode(DriveMode driveMode) {
if (this.driveMode != driveMode) {
LOGGER.d("Updating driveMode: " + driveMode);
this.driveMode = driveMode;
preferencesManager.setDriveMode(driveMode.getValue());
gameController.setDriveMode(driveMode);
driveModeSpinner.setSelection(driveMode.ordinal());
BotToControllerEventBus.emitEvent(
ConnectionUtils.createStatus("DRIVE_MODE", driveMode.toString()));
}
}
protected Model getModel() {
return model;
}
private void setModel(Model model) {
if (this.model != model) {
LOGGER.d("Updating model: " + model);
this.model = model;
preferencesManager.setDefaultModel(model.name);
onInferenceConfigurationChanged();
}
}
protected Device getDevice() {
return device;
}
private void setDevice(Device device) {
if (this.device != device) {
LOGGER.d("Updating device: " + device);
this.device = device;
final boolean threadsEnabled = device == Device.CPU;
plusImageView.setEnabled(threadsEnabled);
minusImageView.setEnabled(threadsEnabled);
threadsTextView.setText(threadsEnabled ? String.valueOf(numThreads) : "N/A");
if (threadsEnabled) threadsTextView.setTextColor(Color.BLACK);
else threadsTextView.setTextColor(Color.GRAY);
preferencesManager.setDevice(device.ordinal());
onInferenceConfigurationChanged();
}
}
protected int getNumThreads() {
return numThreads;
}
private void setNumThreads(int numThreads) {
if (this.numThreads != numThreads) {
LOGGER.d("Updating numThreads: " + numThreads);