Compare commits

..

3 Commits

Author SHA1 Message Date
10e5cb3e61 Added Audio Recorder. Its working 2023-06-18 12:57:50 +02:00
f329fab62d Microphone Detector and Video Detector and Recorder working simultaniously 2023-06-18 11:50:19 +02:00
4baf3db1bb Merge branch 'tw' into bk_video_test
# Conflicts:
#	app/build.gradle
#	app/src/main/AndroidManifest.xml
#	app/src/main/java/com/example/ueberwachungssystem/MainActivity.java
#	app/src/main/res/layout/activity_main.xml
2023-06-18 11:02:20 +02:00
40 changed files with 699 additions and 1782 deletions

Binary file not shown.

View File

@ -26,9 +26,6 @@ android {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildFeatures {
viewBinding true
}
}
dependencies {
@ -36,7 +33,6 @@ dependencies {
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.8.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'com.google.android.gms:play-services-nearby:18.0.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
@ -46,8 +42,6 @@ dependencies {
def opencv_version = "4.5.3.0"
implementation "com.quickbirdstudios:opencv:${opencv_version}"
implementation "androidx.lifecycle:lifecycle-extensions:2.0.0"
// Required for CameraX
def camerax_version = "1.2.2"
@ -57,4 +51,7 @@ dependencies {
implementation "androidx.camera:camera-video:${camerax_version}"
implementation "androidx.camera:camera-view:${camerax_version}"
implementation "androidx.camera:camera-extensions:${camerax_version}"
implementation 'com.jjoe64:graphview:4.2.2'
}

View File

@ -6,8 +6,9 @@
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<!--<uses-permission android:name="android.permission.BLUETOOTH"/>-->
<!--<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
@ -28,7 +29,6 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".Detection.DetectorService"/>
</application>
</manifest>

View File

@ -1,9 +1,8 @@
package com.example.ueberwachungssystem.Detection;
package com.example.ueberwachungssystem;
import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
@ -51,7 +50,6 @@ public class AudioRecorder {
mediaRecorder.release();
mediaRecorder = null;
isRecording = false;
Toast.makeText(context, "audio recording saved", Toast.LENGTH_SHORT).show();
}
}
@ -71,4 +69,15 @@ public class AudioRecorder {
// Return the timestamp as a string
return currentTime.format(formatter);
}
public void playAudio() {
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(context.getFilesDir() + "/audio.3gp");
mp.prepare();
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -1,108 +0,0 @@
package com.example.ueberwachungssystem.Detection;
import static java.lang.Math.sqrt;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
/**
* Accelerometer inherits some methods from abstract Detector class (more info there)
*
*
* USE FROM MAIN ACTIVITY:
*
* Accelerometer beschleunigungssensor = new Accelerometer(this);
* onCreate:
* //Accelerometer Setup
* beschleunigungssensor = new Accelerometer(this, logger, textViewLog); //logger and textview only for debugging necessary
* beschleunigungssensor.getSensor();
*
* //Starting Detection:
* beschleunigungssensor.startDetection();
* //Stopping Detection: also recommended at onPause to avoid unnecessary battery consumption
* beschleunigungssensor.stopDetection();
*
* */
public class Accelerometer extends Detector implements SensorEventListener {
public SensorManager sensorManager;
private static final int sensorType = Sensor.TYPE_LINEAR_ACCELERATION;
private Sensor accelerometer;
private Context context;
boolean alarm = false;
//Preallocate memory for the data of each axis of the acceleration sensor
float x;
float y;
float z;
float betrag; //Betrag aller drei Achsen sqrt(x*x + y*y + z*z)
private DetectionReport detectionReport;
// In constructor pass Activity, Context and TextView from MainActivity in Accelerometer class
public Accelerometer(Context context){
super(); //von Detektor
this.context = context;
}
public void getSensor(){
sensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
if(sensorManager.getSensorList(sensorType).size()==0) {
accelerometer = null;
}
else {
accelerometer = sensorManager.getSensorList(sensorType).get(0);
}
}
@Override
public void onSensorChanged(SensorEvent event) {
try {
checkAlarm(event);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public void checkAlarm (SensorEvent event) throws InterruptedException {
x = event.values[0];
y = event.values[1];
z = event.values[2];
betrag = (float) sqrt(x*x + y*y + z*z);
float threshold = 1.5F;
if (!alarm) {
if (betrag > threshold) {
alarm = true;
reportViolation("Bewegung", betrag);
}
} else {
if (betrag < threshold) {
alarm = false;
} else {
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void startDetection() {
// entspricht void start()
//getSensor();
if (accelerometer != null) {
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);
}
}
@Override
public void stopDetection() {
// entspricht void stop()
sensorManager.unregisterListener(this, accelerometer);
}
}

View File

@ -1,13 +1,8 @@
package com.example.ueberwachungssystem.Detection;
import android.annotation.SuppressLint;
import android.util.Log;
import com.example.ueberwachungssystem.WifiCommunication;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/** Detection Report Class */
public class DetectionReport {
@ -17,11 +12,7 @@ public class DetectionReport {
public boolean detectionState;
public DetectionReport(boolean detectionState, String detectionType, float detectedAmplitude) {
// New Date Format
@SuppressLint("SimpleDateFormat") SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
Date curDate = new Date(System.currentTimeMillis());
this.timeStamp = formatter.format(curDate);
//Old Date Format: this.timeStamp = String.valueOf(Calendar.getInstance().getTime());
this.timeStamp = String.valueOf(Calendar.getInstance().getTime());
this.detectionType = detectionType;
this.detectedValue = detectedAmplitude;
this.detectionState = detectionState;
@ -40,16 +31,6 @@ public class DetectionReport {
return String.join("\t", state, time, type, value);
}
public String toMessage() {
String state;
if(detectionState)
state = "An";
else
state = "Aus";
return String.join(",", "1", timeStamp, "Gruppe2", WifiCommunication.getLocalIpAddress(), state, detectionType, String.valueOf(detectedValue));
}
/** Debug Report */
public void log(String tag) {
Log.d(tag, this.toString());

View File

@ -3,7 +3,6 @@ package com.example.ueberwachungssystem.Detection;
import android.os.CountDownTimer;
import androidx.annotation.NonNull;
import androidx.camera.core.ExperimentalGetImage;
abstract public class Detector {

View File

@ -1,176 +0,0 @@
package com.example.ueberwachungssystem.Detection;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.camera.core.ExperimentalGetImage;
import androidx.lifecycle.LifecycleService;
import com.example.ueberwachungssystem.WifiCommunication;
import java.io.File;
@ExperimentalGetImage
public class DetectorService extends LifecycleService {
public ServiceBinder serviceBinder = new ServiceBinder();
private DetectorService.OnDetectionListener listener;
private boolean isServiceRunning = false;
// Used Objects:
public VideoDetector videoDetector = null;
public AudioRecorder audioRecorder = null;
public Accelerometer motionDetector = null;
public MicrophoneDetector audioDetector = null;
public WifiCommunication wifiCommunication;
String wifiData;
StringBuffer stringBufferWifi = new StringBuffer();
String typOfAlarm;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (isServiceRunning)
return START_NOT_STICKY;
/** Wifi Instanz **/
wifiCommunication = new WifiCommunication(1234);
wifiCommunication.sendTrue("TEst");
wifiCommunication.setOnConnectionListener(new WifiCommunication.OnConnectionListener() {
@Override
public void onConnection(String data) {
Log.d("Listener", data);
wifiData = data;
stringToStringbuffer(data);
Log.d("buffer",stringBufferWifi.toString());
passToServiceListener(stringBufferWifi);
checkState(data);
checkTyp(data);
}
});
/** Video Detection/Recorder **/
videoDetector = new VideoDetector(this);
videoDetector.setOnDetectionListener(new Detector.OnDetectionListener() {
@Override
public void onDetection(@NonNull DetectionReport detectionReport) {
//passToServiceListener(detectionReport);
if(detectionReport.detectionState){
videoDetector.startRecording();
} else {
videoDetector.stopRecording();
}
wifiCommunication.sendTrue(detectionReport.toMessage());
}
});
/** Motion Detection**/
motionDetector = new Accelerometer(this);
motionDetector.getSensor();
motionDetector.setOnDetectionListener(new Detector.OnDetectionListener() {
@Override
public void onDetection(@NonNull DetectionReport detectionReport) {
//passToServiceListener(detectionReport);
wifiCommunication.sendTrue(detectionReport.toMessage());
}
});
/** Audio Detection **/
audioDetector = new MicrophoneDetector(this);
audioDetector.setOnDetectionListener(new Detector.OnDetectionListener() {
@Override
public void onDetection(@NonNull DetectionReport detectionReport) {
//passToServiceListener(detectionReport);
wifiCommunication.sendTrue(detectionReport.toMessage());
}
});
/** Audio Recorder**/
audioRecorder = new AudioRecorder(this);
isServiceRunning = true;
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
isServiceRunning = false;
}
/** Service methods */
public class ServiceBinder extends Binder {
public DetectorService getBoundService() {
// Return an instance of the TestService
return DetectorService.this;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
super.onBind(intent);
return serviceBinder;
}
/** Pass Detection Report to Service Detection Listener and trigger it */
public void passToServiceListener(StringBuffer stringBuffer) {
if (listener != null) {
listener.onDetection(stringBuffer);
}
}
/** On Detection Listener - runs when violation is reported */
public interface OnDetectionListener {
void onDetection(@NonNull StringBuffer stringBuffer);
}
public void setOnDetectionListener(@NonNull DetectorService.OnDetectionListener listener) {
this.listener = listener;
}
public void stringToStringbuffer(String string){
if(string != null) {
stringBufferWifi.insert(0,string + "\n");
}
}
public String[] splitString(String string){
String[] splitrxString = string.split(",");
return splitrxString; //splitrxString[0] = "1",splitrxString[1] = "HH:MM:SS", splitrxString[0].equals("1")
}
public boolean checkState(String string){
Log.d("state", String.valueOf(splitString(string)[4].equals("An")));
return splitString(string)[4].equals("An");
}
public String checkTyp(String string){
if (splitString(string)[5] != null) {
typOfAlarm = splitString(string)[5];
Log.d("Type", typOfAlarm);
}
return typOfAlarm;
}
}

View File

@ -1,109 +0,0 @@
package com.example.ueberwachungssystem.Detection;
import android.graphics.Bitmap;
import android.media.Image;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.camera.core.ExperimentalGetImage;
import androidx.camera.core.ImageProxy;
import org.opencv.android.Utils;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@ExperimentalGetImage
public class OpenCVHelper {
/** OpenCV helper methods **/
public static Mat addGaussianBlur(Mat inputMat, Size kernelSize){
Mat outputMat = new Mat();
Imgproc.GaussianBlur(inputMat, outputMat, kernelSize, 0);
return outputMat;
}
public static Mat addBlur(Mat inputMat, Size kernelSize){
Mat outputMat = new Mat();
Imgproc.blur(inputMat, outputMat, kernelSize);
return outputMat;
}
public static Mat extractYChannel(@NonNull ImageProxy imgProxy) {
Image img = imgProxy.getImage();
assert img != null;
ByteBuffer yBuffer = img.getPlanes()[0].getBuffer();
byte[] yData = new byte[yBuffer.remaining()];
yBuffer.get(yData);
Mat yMat = new Mat(img.getHeight(), img.getWidth(), CvType.CV_8UC1);
yMat.put(0, 0, yData);
return yMat;
}
public static Mat thresholdPixels(Mat inputMat, Mat previousImage, int threshold){
Mat diffImage = new Mat();
Core.absdiff(inputMat, previousImage, diffImage);
Mat binaryMat = new Mat();
Imgproc.threshold(diffImage, binaryMat, threshold, 255, Imgproc.THRESH_BINARY);
return binaryMat;
}
public static Mat thresholdContourArea(Mat inputMat, float areaThreshold){
List<MatOfPoint> contours = new ArrayList<>();
Mat hierarchy = new Mat();
Imgproc.findContours(inputMat, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
Mat outputMat = new Mat(inputMat.size(), inputMat.type(), new Scalar(0));
// Iterate over the contours and draw only the larger contours on the outputMat
for (MatOfPoint contour : contours) {
double contourArea = Imgproc.contourArea(contour);
if (contourArea > areaThreshold) {
Imgproc.drawContours(outputMat, Collections.singletonList(contour), 0, new Scalar(255), -1);
}
}
// Apply the outputMat as a mask to the dilatedImage
Mat maskedImage = new Mat();
inputMat.copyTo(maskedImage, outputMat);
return outputMat;
}
public static Mat dilateBinaryMat(Mat inputMat, Size kernelSize){
Mat dilatedMat = new Mat();
Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, kernelSize);
Imgproc.dilate(inputMat, dilatedMat, kernel);
return dilatedMat;
}
public static int countNonZeroPixels(Mat inputImage) {
if (inputImage != null)
return Core.countNonZero(inputImage);
else
return 0;
}
public static void debugMat(Mat mat, ImageView imageView) {
if (imageView == null || mat == null)
return;
Bitmap bitmap = Bitmap.createBitmap(mat.cols(), mat.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(mat, bitmap);
// Display the bitmap in an ImageView
imageView.setImageBitmap(bitmap);
}
}

View File

@ -2,15 +2,15 @@ package com.example.ueberwachungssystem.Detection;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.ImageFormat;
import android.media.Image;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;
@ -31,30 +31,44 @@ import androidx.lifecycle.LifecycleOwner;
import com.google.common.util.concurrent.ListenableFuture;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
/**
* Video Detector inherits some methods from abstract Detector class (more info there)
* USE FROM MAIN ACTIVITY:
* VideoDetector vd = new VideoDetector(this);
* */
@ExperimentalGetImage
public class VideoDetector extends Detector {
// Calling Activity
private final Context context;
// Permission handling
private static final int PERMISSION_REQUEST_CODE = 3691;
// Camera Provider
private ProcessCameraProvider cameraProvider;
private ImageAnalysis imageAnalysis;
private VideoCapture videoCapture;
//private Preview preview;
private final ImageAnalysis imageAnalysis;
private final VideoCapture videoCapture;
private final Preview preview;
// Logic
private boolean isDetecting = false;
@ -68,18 +82,23 @@ public class VideoDetector extends Detector {
private ImageView inputImageView = null;
private ImageView outputImageView = null;
// Recorder
private File outputDir; // Default: in app files directory
// Recording
private final String outputName = "video.mp4";
// Parameters
private static final float ALARM_THRESHOLD = 0f; // Percent of pixels changed
private static final float AREA_THRESHOLD = 10f;
private static final int DILATE_ITERATIONS = 2;
private static final float START_DELAY = 2000; // milliseconds
private static final float ALARM_THRESHOLD = 0.5f; // Percent of pixels changed
private static final long START_DELAY = 20000; // milliseconds
private static final android.util.Size IMAGE_RES = new android.util.Size(640, 480);
private enum UseCase {
ImageAnalysis,
Preview,
VideoCapture
};
/** Constructor */
public VideoDetector(Context context) {
@ -87,17 +106,13 @@ public class VideoDetector extends Detector {
this.context = context;
this.imageAnalysis = setupImageAnalysis();
this.videoCapture = setupVideoCapture();
this.outputDir = context.getFilesDir();
//this.preview = new Preview.Builder().build();
this.preview = new Preview.Builder().build();
}
/** Get States */
public boolean isDetecting() {
/** Get State of the Detector */
public boolean isRunning() {
return isDetecting;
}
public boolean isRecording(){
return isRecording;
}
/** Starts the Video Detection */
@ -106,8 +121,11 @@ public class VideoDetector extends Detector {
// Check States
if (isDetecting)
return;
// Configure Image Analysis
imageAnalysis = setupImageAnalysis();
// Return On Request Permissions
if (!hasPermissions()) {
getPermissions();
return;
}
// Open CV startup check
if (!OpenCVLoader.initDebug()) {
Log.e("OpenCV", "Unable to load OpenCV!");
@ -120,52 +138,11 @@ public class VideoDetector extends Detector {
try {
cameraProvider = cameraProviderFuture.get();
isDetecting = true;
bindCameraProvider();
bindCameraProvider(UseCase.ImageAnalysis);
} catch (ExecutionException | InterruptedException e) {}
}, ContextCompat.getMainExecutor(context));
// Disable Violation Calling for Setup Time
startViolationTimer(START_DELAY);
}
/** Starts the Recorder */
@SuppressLint("RestrictedApi")
public void startRecording() {
// Check States
if (isRecording){
return;
}
Toast.makeText(context, "Aufnahme gestartet", Toast.LENGTH_SHORT).show();
videoCapture = setupVideoCapture();
final ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(context);
cameraProviderFuture.addListener(() -> {
try {
cameraProvider = cameraProviderFuture.get();
isRecording = true;
bindCameraProvider();
File vidFile = new File(context.getFilesDir() + "/" + generateFileName() + ".mp4");
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
return;
}
videoCapture.startRecording(
new VideoCapture.OutputFileOptions.Builder(vidFile).build(),
context.getMainExecutor(),
new VideoCapture.OnVideoSavedCallback() {
@Override
public void onVideoSaved(@NonNull VideoCapture.OutputFileResults outputFileResults) {
isRecording = false;
Toast.makeText(context, "Aufnahme gespeichert", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(int videoCaptureError, @NonNull String message, @Nullable Throwable cause) {
isRecording = false;
Toast.makeText(context, "Aufnahme fehlgeschlagen", Toast.LENGTH_SHORT).show();
}
}
);
} catch (ExecutionException | InterruptedException ignored) {}
}, ContextCompat.getMainExecutor(context));
startViolationTimer();
}
/** Stops the Video Detection */
@ -173,149 +150,35 @@ public class VideoDetector extends Detector {
public void stopDetection() {
if (!isDetecting || imageAnalysis == null)
return;
if (!isRecording)
cameraProvider.unbindAll();
else
cameraProvider.unbind(imageAnalysis);
cameraProvider.unbind(imageAnalysis);
isDetecting = false;
allowReportViolation = false;
}
/** Stops the Recording */
@SuppressLint("RestrictedApi")
public void stopRecording(){
if(!isRecording)
return;
videoCapture.stopRecording();
if (!isDetecting())
cameraProvider.unbindAll();
else
cameraProvider.unbind(videoCapture);
isRecording = false;
/** Permission handling */
private boolean hasPermissions() {
return ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
}
private void getPermissions() {
if (!hasPermissions())
ActivityCompat.requestPermissions((Activity) context, new String[]{android.Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO}, PERMISSION_REQUEST_CODE);
}
/** Bind Camera Provider */
private void bindCameraProvider() {
/** Binds the Luminosity Analyzer (configure and run Analysis) */
private void bindCameraProvider(UseCase useCase) {
// Specify which Camera to use
CameraSelector cameraSelector = new CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build();
cameraProvider.unbindAll();
cameraProvider.bindToLifecycle((LifecycleOwner) context, cameraSelector, imageAnalysis, videoCapture);
}
/** Setup Use Cases */
private ImageAnalysis setupImageAnalysis() {
// Configure and create Image Analysis
ImageAnalysis.Builder builder = new ImageAnalysis.Builder();
builder.setTargetResolution(IMAGE_RES);
builder.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST);
builder.setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888);
builder.setTargetRotation(Surface.ROTATION_90);
ImageAnalysis imageAnalysis = builder.build();
// Set Analyzer
imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(context), imageProxy -> {
if (imageProxy.getFormat() == ImageFormat.YUV_420_888) {
Image image = imageProxy.getImage();
assert image != null;
// Violation Handling
Mat processed = processImage(imageProxy);
int n = OpenCVHelper.countNonZeroPixels(processed);
int pixelCount = image.getWidth() * image.getHeight();
float percentChanged = ((float) n / pixelCount) * 100;
// Violation Condition
if (percentChanged> ALARM_THRESHOLD) {
if (allowReportViolation)
reportViolation("Video", percentChanged);
}
}
imageProxy.close();
});
return imageAnalysis;
}
@SuppressLint("RestrictedApi")
private VideoCapture setupVideoCapture() {
int rotation = getDisplayRotation();
return new VideoCapture.Builder()
.setTargetRotation(rotation)
.build();
}
/** Process Image to be used for Motion Detection */
private Mat processImage(ImageProxy imageProxy){
if (imageProxy == null)
return null;
// Image Transformation
Mat imageMat = OpenCVHelper.extractYChannel(imageProxy);
// Show Input Image
if (inputImageView != null)
OpenCVHelper.debugMat(imageMat, inputImageView);
// Preprocess Image
Mat preprocessed = imageMat;
preprocessed = OpenCVHelper.addGaussianBlur(preprocessed, new Size(21, 21));
preprocessed = OpenCVHelper.addBlur(preprocessed, new Size(3, 3));
// Set Previous Image
if (previousImage == null) {
previousImage = preprocessed;
return null;
}
// Process Image
Mat processed = preprocessed.clone();
processed = OpenCVHelper.thresholdPixels(processed, previousImage, 25);
for(int i = 0; i < DILATE_ITERATIONS; i++)
processed = OpenCVHelper.dilateBinaryMat(processed, new Size(3,3));
processed = OpenCVHelper.thresholdContourArea(processed, AREA_THRESHOLD);
// Output
previousImage = preprocessed.clone();
// Show Output Image
if (outputImageView != null)
OpenCVHelper.debugMat(processed, outputImageView);
return processed;
}
/** Debug input and result of processing */
public void debugProcessing(@NonNull ImageView inputImageView, @NonNull ImageView outputImageView){
this.inputImageView = inputImageView;
this.outputImageView = outputImageView;
}
/**
private void setPreviewView(@NonNull PreviewView previewView) {
// Create Preview
if (this.preview != null)
this.preview.setSurfaceProvider(previewView.getSurfaceProvider());
}
*/
/** Generate File Name */
private String generateFileName(){
// Get the current timestamp
LocalDateTime currentTime = LocalDateTime.now();
// Define the format for the timestamp
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
// Return the timestamp as a string
return currentTime.format(formatter);
}
/** Get current Display Rotation */
private int getDisplayRotation() {
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
return display.getRotation();
}
/** Start delay until Violation Report is allowed */
private void startViolationTimer(float setupTime) {
new CountDownTimer((long) (setupTime), 100) {
private void startViolationTimer() {
new CountDownTimer((long) (START_DELAY), 100) {
@Override
public void onTick(long millisUntilFinished) {
}
@ -326,7 +189,253 @@ public class VideoDetector extends Detector {
}.start();
}
public void setOutputDir(File outputDir) {
this.outputDir = outputDir;
private ImageAnalysis setupImageAnalysis() {
// Configure and create Image Analysis
ImageAnalysis.Builder builder = new ImageAnalysis.Builder();
builder.setTargetResolution(IMAGE_RES);
builder.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST);
builder.setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888);
ImageAnalysis imageAnalysis = builder.build();
// Set Analyzer
imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(context), imageProxy -> {
if (imageProxy.getFormat() == ImageFormat.YUV_420_888) {
Image image = imageProxy.getImage();
assert image != null;
// Violation Handling
Mat processed = processImage(imageProxy);
int n = OpenCVHelper.countNonZeroPixels(processed);
int pixelCount = image.getWidth() * image.getHeight();
float percentChanged = (float) n / pixelCount;
// Violation Condition
if (percentChanged * 100 > ALARM_THRESHOLD) {
if (allowReportViolation)
reportViolation("Video", n);
}
}
imageProxy.close();
});
return imageAnalysis;
}
@SuppressLint("RestrictedApi")
private VideoCapture setupVideoCapture() {
return new VideoCapture.Builder()
.setTargetRotation(Surface.ROTATION_0)
.build();
}
@SuppressLint("RestrictedApi")
public void startRecording() {
// Check States
if (isRecording){
extendViolation();
return;
}
// Return On Request Permissions
if (!hasPermissions()) {
getPermissions();
return;
}
final ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(context);
cameraProviderFuture.addListener(() -> {
try {
cameraProvider = cameraProviderFuture.get();
isRecording = true;
bindCameraProvider(UseCase.VideoCapture);
File vidFile = new File(context.getFilesDir() + "/" + outputName);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
return;
}
videoCapture.startRecording(
new VideoCapture.OutputFileOptions.Builder(vidFile).build(),
context.getMainExecutor(),
new VideoCapture.OnVideoSavedCallback() {
@Override
public void onVideoSaved(@NonNull VideoCapture.OutputFileResults outputFileResults) {
isRecording = false;
Toast.makeText(context, "recording saved", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(int videoCaptureError, @NonNull String message, @Nullable Throwable cause) {
isRecording = false;
Toast.makeText(context, "recording failed", Toast.LENGTH_SHORT).show();
}
}
);
} catch (ExecutionException | InterruptedException e) {}
}, ContextCompat.getMainExecutor(context));
}
@SuppressLint("RestrictedApi")
public void stopRecording(){
videoCapture.stopRecording();
cameraProvider.unbind(videoCapture);
isRecording = false;
}
/** Process Image to be used for Motion Detection */
private Mat processImage(ImageProxy imageProxy){
if (imageProxy == null)
return null;
// Image Transformation
Mat imageMat = OpenCVHelper.extractYChannel(imageProxy);
// Show Input Image
if (inputImageView != null)
OpenCVHelper.debugMat(imageMat, inputImageView);
// Preprocess Image
Mat preprocessed = imageMat;
preprocessed = OpenCVHelper.addGaussianBlur(preprocessed, new Size(21, 21));
preprocessed = OpenCVHelper.addBlur(preprocessed, new Size(3, 3));
if (previousImage == null) {
previousImage = preprocessed;
return null;
}
// Process Image
Mat processed = preprocessed.clone();
processed = OpenCVHelper.thresholdPixels(processed, previousImage, 25);
processed = OpenCVHelper.dilateBinaryMat(processed, new Size(3,3));
processed = OpenCVHelper.dilateBinaryMat(processed, new Size(3,3));
processed = OpenCVHelper.thresholdContourArea(processed, 500);
// Output
previousImage = preprocessed.clone();
// Show Output Image
if (outputImageView != null)
OpenCVHelper.debugMat(processed, outputImageView);
return processed;
}
public void debugProcessing(@NonNull ImageView inputImageView, @NonNull ImageView outputImageView){
this.inputImageView = inputImageView;
this.outputImageView = outputImageView;
}
public void setPreviewView(@NonNull PreviewView previewView) {
// Create Preview
if (this.preview != null)
this.preview.setSurfaceProvider(previewView.getSurfaceProvider());
}
private static class OpenCVHelper{
private OpenCVHelper() {}
/** OpenCV helper methods **/
private static Mat addGaussianBlur(Mat inputMat, Size kernelSize){
Mat outputMat = new Mat();
Imgproc.GaussianBlur(inputMat, outputMat, kernelSize, 0);
return outputMat;
}
private static Mat addBlur(Mat inputMat, Size kernelSize){
Mat outputMat = new Mat();
Imgproc.blur(inputMat, outputMat, kernelSize);
return outputMat;
}
private static Mat extractYChannel(@NonNull ImageProxy imgProxy) {
Image img = imgProxy.getImage();
assert img != null;
ByteBuffer yBuffer = img.getPlanes()[0].getBuffer();
byte[] yData = new byte[yBuffer.remaining()];
yBuffer.get(yData);
Mat yMat = new Mat(img.getHeight(), img.getWidth(), CvType.CV_8UC1);
yMat.put(0, 0, yData);
return yMat;
}
private static Mat thresholdPixels(Mat inputMat, Mat previousImage, int threshold){
Mat diffImage = new Mat();
Core.absdiff(inputMat, previousImage, diffImage);
Mat binaryMat = new Mat();
Imgproc.threshold(diffImage, binaryMat, threshold, 255, Imgproc.THRESH_BINARY);
return binaryMat;
}
private static Mat imageProxyToGrayscaleMat(ImageProxy imageProxy) {
// Step 1: Extract the image data from ImageProxy
ImageProxy.PlaneProxy[] planes = imageProxy.getPlanes();
ByteBuffer yBuffer = planes[0].getBuffer();
byte[] yData = new byte[yBuffer.remaining()];
yBuffer.get(yData);
// Step 2: Convert the image data to NV21 format
int width = imageProxy.getWidth();
int height = imageProxy.getHeight();
byte[] nv21Data = new byte[width * height * 3 / 2];
// Assuming the image format is YUV_420_888
System.arraycopy(yData, 0, nv21Data, 0, yData.length);
for (int i = yData.length; i < nv21Data.length; i += 2) {
nv21Data[i] = yData[i + 1];
nv21Data[i + 1] = yData[i];
}
// Step 3: Create a grayscale Mat from the NV21 data
Mat grayscaleMat = new Mat(height, width, CvType.CV_8UC1);
grayscaleMat.put(0, 0, nv21Data);
return grayscaleMat;
}
private static Mat thresholdContourArea(Mat inputMat, float areaThreshold){
List<MatOfPoint> contours = new ArrayList<>();
Mat hierarchy = new Mat();
Imgproc.findContours(inputMat, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
Mat outputMat = new Mat(inputMat.size(), inputMat.type(), new Scalar(0));
// Iterate over the contours and draw only the larger contours on the outputMat
for (MatOfPoint contour : contours) {
double contourArea = Imgproc.contourArea(contour);
if (contourArea > areaThreshold) {
Imgproc.drawContours(outputMat, Collections.singletonList(contour), 0, new Scalar(255), -1);
}
}
// Apply the outputMat as a mask to the dilatedImage
Mat maskedImage = new Mat();
inputMat.copyTo(maskedImage, outputMat);
return outputMat;
}
private static Mat dilateBinaryMat(Mat inputMat, Size kernelSize){
Mat dilatedMat = new Mat();
Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, kernelSize);
Imgproc.dilate(inputMat, dilatedMat, kernel);
return dilatedMat;
}
private static int countNonZeroPixels(Mat inputImage) {
if (inputImage != null)
return Core.countNonZero(inputImage);
else
return 0;
}
private static void debugMat(Mat mat, ImageView imageView) {
if (imageView == null || mat == null)
return;
Bitmap bitmap = Bitmap.createBitmap(mat.cols(), mat.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(mat, bitmap);
// Display the bitmap in an ImageView
imageView.setImageBitmap(bitmap);
}
}
}

View File

@ -0,0 +1,36 @@
package com.example.ueberwachungssystem;
import android.util.Log;
import java.util.Calendar;
/** Detection Report Class */
public class DetectionReport {
public String timeStamp;
public String detectionType;
public float detectedValue;
public String detectorID;
public DetectionReport(String detectorID, String detectionType, float detectedAmplitude) {
this.timeStamp = String.valueOf(Calendar.getInstance().getTime());
this.detectionType = detectionType;
this.detectedValue = detectedAmplitude;
this.detectorID = detectorID;
}
/** Get Detection Report in String format */
public String toString() {
String time = "Time: " + "[" + this.timeStamp + "]";
String type = "Type: " + "[" + this.detectionType + "]";
String value = "Value: " + "[" + this.detectedValue + "]";
String id = "ID: " + "[" + this.detectorID + "]";
return String.join("\t", time, type, value, id);
}
/** Debug Report */
public void log(String tag) {
Log.d(tag, this.toString());
}
}

View File

@ -0,0 +1,40 @@
package com.example.ueberwachungssystem;
import android.app.Activity;
import android.content.Context;
import androidx.annotation.NonNull;
abstract public class Detector {
private OnDetectionListener listener;
/** Constructor - takes context of current activity */
public Detector(Context context) {};
/** On Detection Listener - runs when violation is reported */
public interface OnDetectionListener {
void onDetection(@NonNull DetectionReport detectionReport);
}
public void setOnDetectionListener(@NonNull OnDetectionListener listener) {
this.listener = listener;
}
/** Triggers onDetectionListener - call this to trigger violation/alarm */
private void reportViolation(String detectorID, String detectionType, float amplitude) {
if (listener != null) {
DetectionReport detectionReport = new DetectionReport(detectorID, detectionType, amplitude);
listener.onDetection(detectionReport);
} else {
throw new IllegalStateException("No listener set for violation reporting");
}
}
/** Starts Detection (abstract method: needs to be overridden in child class) */
public abstract void startDetection();
/** Stops Detection (abstract method: needs to be overridden in child class) */
public abstract void stopDetection();
}

View File

@ -1,61 +0,0 @@
package com.example.ueberwachungssystem.Fragments;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.VideoView;
import androidx.fragment.app.Fragment;
import com.example.ueberwachungssystem.R;
import java.io.File;
public class Fragment1 extends Fragment {
private String text;
private final static String KEY_TEXT = "KEY_TEXT";
private void log(String nachricht) {
Log.d(this.getClass().getSimpleName(), nachricht);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
log("onCreateView");
View view = inflater.inflate(R.layout.fragment1, container, false);
TextView Sensor = (TextView) view.findViewById(R.id.Alarm);
Sensor.setText(text);
return view;
}
public static Fragment1 erstellen(String text) {
Fragment1 fragment = new Fragment1();
Bundle b = new Bundle();
b.putString(KEY_TEXT, text);
fragment.setArguments(b);
return fragment;
}
public static Fragment1 aktualisieren(String text){
Fragment1 fragment = new Fragment1();
Bundle b = new Bundle();
b.putString(KEY_TEXT, text);
fragment.setArguments(b);
return fragment;
}
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
Bundle args = getArguments();
if (args != null ) {
text = args.getString(KEY_TEXT);
log("onCreate: text=" + text);
} else {
log("onCreate");
}
}
}

View File

@ -1,62 +0,0 @@
package com.example.ueberwachungssystem.Fragments;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.fragment.app.Fragment;
import com.example.ueberwachungssystem.R;
public class Fragment3 extends Fragment {
private OnImageViewReadyListener onImageViewReadyListener;
private String text;
public static ImageView ivp;
private final static String KEY_TEXT = "KEY_TEXT";
private void log(String nachricht) {
Log.d(this.getClass().getSimpleName(), nachricht);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
log("onCreateView");
View view = inflater.inflate(R.layout.fragment3, container, false);
if (onImageViewReadyListener != null) {
ImageView ivp = (ImageView) view.findViewById(R.id.Video);
ImageView ivp2 = (ImageView) view.findViewById(R.id.Video2);
onImageViewReadyListener.onImageViewReady(ivp, ivp2);
}
return view;
}
public static Fragment3 erstellen(View view) {
Fragment3 fragment = new Fragment3();
return fragment;
}
public interface OnImageViewReadyListener {
void onImageViewReady(ImageView imageView, ImageView imageView2);
}
public void onAttach(Context context) {
super.onAttach(context);
try {
onImageViewReadyListener = (OnImageViewReadyListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement OnImageViewReadyListener");
}
}
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
Bundle args = getArguments();
if (args != null ) {
text = args.getString(KEY_TEXT);
log("onCreate: text=" + text);
} else {
log("onCreate");
}
}
}

View File

@ -1,104 +0,0 @@
package com.example.ueberwachungssystem.Fragments;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;
import android.widget.VideoView;
import androidx.fragment.app.Fragment;
import com.example.ueberwachungssystem.R;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class VideoListFragment extends Fragment {
private ListView listView;
private Button button;
private ArrayAdapter<String> adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.videolist_fragment, container, false);
button = rootView.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
File dir = getContext().getFilesDir();
File[] files = dir.listFiles();
for (File file: files) {
file.delete();
}
}
});
listView = rootView.findViewById(R.id.listView);
adapter = new ArrayAdapter<>(requireContext(), android.R.layout.simple_list_item_1, getFileNames());
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Handle item click event here
String selectedItem = getContext().getFilesDir().toString() + "/" + adapter.getItem(position);
//Toast.makeText(requireContext(), selectedItem, Toast.LENGTH_SHORT).show();
openVideoPopup(selectedItem);
}
});
return rootView;
}
private List<String> getFileNames() {
// Add your data source here, e.g., an array or a list
File dir = getContext().getFilesDir();
File[] files = dir.listFiles();
Log.d("files", getContext().getFilesDir().toString());
List<String> fileNamesList = new ArrayList<>();
assert files != null;
for (File file : files) {
fileNamesList.add(file.getName());
}
return fileNamesList;
}
private void openVideoPopup(String videoPath) {
LayoutInflater inflater = LayoutInflater.from(requireContext());
View popupView = inflater.inflate(R.layout.videolist_popup, null);
VideoView videoView = popupView.findViewById(R.id.videoView);
videoView.setVideoPath(videoPath);
videoView.start();
PopupWindow popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
popupView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
//Close the window when clicked
popupWindow.dismiss();
return true;
}
});
popupWindow.showAtLocation(listView, Gravity.CENTER, 0, 0);
}
}

View File

@ -1,233 +1,78 @@
package com.example.ueberwachungssystem;
import androidx.camera.core.ExperimentalGetImage;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.ExperimentalGetImage;
import androidx.camera.view.PreviewView;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.example.ueberwachungssystem.Fragments.Fragment1;
import com.example.ueberwachungssystem.Detection.DetectorService;
import com.example.ueberwachungssystem.Fragments.Fragment3;
import com.example.ueberwachungssystem.Fragments.VideoListFragment;
import java.util.OptionalInt;
import com.example.ueberwachungssystem.Detection.DetectionReport;
import com.example.ueberwachungssystem.Detection.Detector;
import com.example.ueberwachungssystem.Detection.VideoDetector;
import com.example.ueberwachungssystem.logger.Logger;
import com.jjoe64.graphview.GraphView;
@ExperimentalGetImage
public class MainActivity extends AppCompatActivity implements Fragment3.OnImageViewReadyListener{
//StringBuffer
private StringBuffer messageBuffer = new StringBuffer();
//Fragmente
private Fragment aktuellesFragment;
private Fragment fragment1_;
private Fragment fragment2_;
private Fragment fragment3_;
private Fragment1 fragment1;
private Fragment3 fragment3;
private ImageView fragmentImage;
private ImageView fragmentImage2;
private VideoListFragment videoListFragment = new VideoListFragment();
private DetectorService detectorService = new DetectorService();
int num = 0;
//Textviews
private TextView Auswahl;
private TextView AoderA;
private String auswahltext = "Wahl des Detektionsmodus";
private String auswahlAoderA = "Wahl von Alarmmeldungen oder Auswahl von Alarmaufzeichnungen";
//Buttons
private ToggleButton toggleKamera;
private ToggleButton toggleAudio;
private ToggleButton toggleBewegung;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Supervision");
setContentView(R.layout.activity_main);
Auswahl = findViewById(R.id.textAuswahl);
Auswahl.setText(auswahltext);
AoderA = findViewById(R.id.textAoderA);
AoderA.setText(auswahlAoderA);
toggleKamera = findViewById(R.id.toggleKamera);
toggleAudio = findViewById(R.id.toggleAudio);
toggleBewegung = findViewById(R.id.toggleBewegung);
}
@Override
protected void onResume() {
super.onResume();
PermissionHandler permissionHandler = new PermissionHandler(this);
//permissionHandler.getPermissions();
if (permissionHandler.hasPermissions()) {
ImageView inputImageView = findViewById(R.id.inputImageView);
ImageView outputImageView = findViewById(R.id.outputImageView);
PreviewView previewView = findViewById(R.id.previewView);
Intent serviceIntent = new Intent(this, DetectorService.class);
bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
startService(serviceIntent);
toggleKamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (toggleKamera.isChecked()) {
if(detectorService != null) {
detectorService.videoDetector.startDetection();
}
} else {
if(detectorService != null) {
detectorService.videoDetector.stopDetection();
}
}
// Mic stuff
TextView textView= (TextView) findViewById(R.id.textView); //Set textview for showing logged content
Logger logger = new Logger(this.getClass().getSimpleName(), textView, "");
GraphView graph = (GraphView) findViewById(R.id.graph);
MicrophoneDetector mic = new MicrophoneDetector(this, logger, graph);
mic.startDetection();
AudioRecorder audioRecorder = new AudioRecorder(this);
// video Stuff
VideoDetector vd = new VideoDetector(this);
//vd.setPreviewView(previewView);
vd.debugProcessing(inputImageView, outputImageView);
vd.setOnDetectionListener(new Detector.OnDetectionListener() {
@Override
public void onDetection(@NonNull DetectionReport detectionReport) {
Log.d("onDetection", detectionReport.toString());
}
});
vd.startDetection();
ToggleButton toggleButton = findViewById(R.id.toggleButton);
toggleButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (toggleButton.isChecked())
{
//vd.startDetection();
vd.startRecording();
audioRecorder.startRecording();
}
});
toggleAudio.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (toggleAudio.isChecked()) {
if(detectorService != null) {
detectorService.audioDetector.startDetection();
}
} else {
if(detectorService != null) {
detectorService.audioDetector.stopDetection();
}
}
else {
//vd.stopDetection();
vd.stopRecording();
audioRecorder.stopRecording();
}
});
toggleBewegung.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (toggleBewegung.isChecked()) {
if(detectorService != null) {
detectorService.motionDetector.startDetection();
}
} else {
if(detectorService != null) {
detectorService.motionDetector.stopDetection();
}
}
}
});
}else{
Toast.makeText(this,"Bitte Rechte geben", Toast.LENGTH_SHORT).show();
}
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.options_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
Toast.makeText(this, "Selected Item: " + item.getTitle(), Toast.LENGTH_SHORT).show();
PopUpClass popUpClass;
switch (item.getItemId()) {
case R.id.Rechteverwaltung:
popUpClass = new PopUpClass(MainActivity.this);
popUpClass.showPopupWindow(toggleAudio);
popUpClass.RechtePrüfen();
return true;
case R.id.Sensoren:
popUpClass = new PopUpClass(MainActivity.this);
popUpClass.showPopupWindow(toggleAudio);
popUpClass.Sensoren();
return true;
case R.id.Impressum:
popUpClass = new PopUpClass(MainActivity.this);
popUpClass.showPopupWindow(toggleAudio);
popUpClass.Impressum();
return true;
case R.id.Detection:
popUpClass = new PopUpClass(MainActivity.this);
popUpClass.showPopupWindow(toggleAudio);
popUpClass.DetectionTotal(num);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
DetectorService.ServiceBinder binder = (DetectorService.ServiceBinder) service;
detectorService = binder.getBoundService();
detectorService.setOnDetectionListener(new DetectorService.OnDetectionListener() {
@Override
public void onDetection(@NonNull StringBuffer stringBuffer) {
Log.d("onDetection", stringBuffer.toString()); //Für oli hier Textview einbauen
num = stringBuffer.toString().split("\n").length;
messageBuffer = stringBuffer;
if ((aktuellesFragment == fragment1_) && (aktuellesFragment != null)) {
Log.d("Fragment", aktuellesFragment.toString() + " " + fragment1_.toString());
fragment1_ = zeigeFragment(fragment1.erstellen(messageBuffer.toString()));
}
}
});
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
public void onClickZeigeFragment1(View view) {
Button button = (Button) view;
fragment1_ = zeigeFragment(fragment1.erstellen(messageBuffer.toString()));
}
public void onClickZeigeFragment2(View view) {
Button button = (Button) view;
//zeigeFragment(fragment2.erstellen("Hier stehen dann die Videos"));
fragment2_ = zeigeFragment(videoListFragment);
}
public void onClickZeigeFragment3(View view) {
Button button = (Button) view;
fragment3_ = zeigeFragment(fragment3.erstellen(view));
}
public void onImageViewReady(ImageView imageView, ImageView imageView2) {
fragmentImage = imageView;
fragmentImage2 = imageView2;
detectorService.videoDetector.debugProcessing(fragmentImage, fragmentImage2); //inputImageView
}
public void onClickEntferneFragment(View view) {
entferneFragment();
}
private Fragment zeigeFragment(Fragment fragment) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.frame, fragment);
ft.commit();
aktuellesFragment = fragment;
return aktuellesFragment;
}
private void entferneFragment() {
if (aktuellesFragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.remove(aktuellesFragment);
ft.commit();
aktuellesFragment = null ;
}
}
});
}
}

View File

@ -1,17 +1,25 @@
package com.example.ueberwachungssystem.Detection;
package com.example.ueberwachungssystem;
import static java.lang.Math.*;
import android.annotation.SuppressLint;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.AsyncTask;
import android.util.Log;
import com.example.ueberwachungssystem.Detection.Signalverarbeitung.Complex;
import com.example.ueberwachungssystem.Detection.Signalverarbeitung.FFT;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.example.ueberwachungssystem.Signalverarbeitung.Complex;
import com.example.ueberwachungssystem.Signalverarbeitung.FFT;
import com.example.ueberwachungssystem.logger.Logger;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
public class MicrophoneDetector extends Detector {
/**
@ -20,56 +28,98 @@ public class MicrophoneDetector extends Detector {
* @param context
*/
private static final int RECHTEANFORDERUNG_MIKROFON = 1;
private AufnahmeTask aufnahmeTask;
public boolean armed = false;
public int schwellwertAlarm = 100;
private Context context;
public int Schwellwert_Alarm = 100;
GraphView graph;
public MicrophoneDetector(Context context) {
super();
this.context = context;
Logger logger;
private Activity MainActivityForClass;
public MicrophoneDetector(Context context, Logger MainLogger, GraphView MainGraph) {
super(context);
MainActivityForClass = (Activity) context;
logger = MainLogger; //Class uses the same logger as the MainActivity
logger.log(this.getClass().getSimpleName() + ".onCreate");
graph = MainGraph;
if (!istZugriffAufMikrofonErlaubt()) {
zugriffAufMikrofonAnfordern();
}
}
@Override
public void startDetection() {
aufnahmeTask = new AufnahmeTask();
aufnahmeTask.execute();
logger.log(this.getClass().getSimpleName() + ".startDetection");
if (!istZugriffAufMikrofonErlaubt()) {
zugriffAufMikrofonAnfordern();
}
if (istZugriffAufMikrofonErlaubt()) {
aufnahmeTask = new AufnahmeTask();
aufnahmeTask.execute();
}
}
@Override
public void stopDetection() {
logger.log(this.getClass().getSimpleName() + ".stopDetection");
if (aufnahmeTask != null) {
aufnahmeTask.cancel(true);
// aufnahmeTask = null; // if aufnahmeTask = null, break in for loop would not work (Nullpointer Exception)
}
}
private boolean istZugriffAufMikrofonErlaubt() {
if (ContextCompat.checkSelfPermission(MainActivityForClass, android.Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
logger.log("Zugriff auf Mikrofon ist verboten.");
return false;
} else {
logger.log("Zugriff auf Mikrofon ist erlaubt.");
return true;
}
}
private void zugriffAufMikrofonAnfordern() {
ActivityCompat.requestPermissions(MainActivityForClass, new String[]{Manifest.permission.RECORD_AUDIO}, RECHTEANFORDERUNG_MIKROFON);
}
class AufnahmeTask extends AsyncTask<Long, Verarbeitungsergebnis, Void> {
private AudioRecord recorder;
private final int sampleRateInHz = 44100;
private final int channelConfig = AudioFormat.CHANNEL_IN_MONO;
private final int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
private final int startDelay = 2000;
private final int threadSleeptime = 10;
private int minPufferGroesseInBytes;
private int pufferGroesseInBytes;
private RingPuffer ringPuffer = new RingPuffer(10);
private float kalibierWert;
private com.example.ueberwachungssystem.Detection.DetectionReport detectionReport;
private DetectionReport detectionReport;
@SuppressLint("MissingPermission")
AufnahmeTask() {
minPufferGroesseInBytes = AudioRecord.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat);
pufferGroesseInBytes = minPufferGroesseInBytes * 2;
try {
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRateInHz, channelConfig, audioFormat, pufferGroesseInBytes);
} catch (Exception e) {
e.printStackTrace();
if (ActivityCompat.checkSelfPermission(MainActivityForClass, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
ActivityCompat.requestPermissions(MainActivityForClass, new String[]{Manifest.permission.RECORD_AUDIO}, RECHTEANFORDERUNG_MIKROFON);
}
Log.d("0","Puffergroeße: "+ minPufferGroesseInBytes + " " + pufferGroesseInBytes);
Log.d("0","Recorder (SR, CH): "+ recorder.getSampleRate() + " " + recorder.getChannelCount());
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRateInHz, channelConfig, audioFormat, pufferGroesseInBytes);
// textViewMinPufferGroesseInBytes.setText("" + minPufferGroesseInBytes);
// textViewPufferGroesseInBytes.setText("" + pufferGroesseInBytes);
// textViewAbtastrate.setText("" + recorder.getSampleRate());
// textViewAnzahlKanaele.setText("" + recorder.getChannelCount());
logger.log("Puffergroeße: "+ minPufferGroesseInBytes + " " + pufferGroesseInBytes);
logger.log("Recorder (SR, CH): "+ recorder.getSampleRate() + " " + recorder.getChannelCount());
int anzahlBytesProAbtastwert;
String s;
@ -89,6 +139,7 @@ public class MicrophoneDetector extends Detector {
default:
throw new IllegalArgumentException();
}
// textViewAudioFormat.setText(s);
switch (recorder.getChannelConfiguration()) {
case AudioFormat.CHANNEL_IN_MONO:
@ -104,9 +155,14 @@ public class MicrophoneDetector extends Detector {
default:
throw new IllegalArgumentException();
}
// textViewKanalKonfiguration.setText(s);
logger.log("Konfiguration: "+ s);
Log.d("0","Konfiguration: "+ s);
int pufferGroesseInAnzahlAbtastwerten = pufferGroesseInBytes / anzahlBytesProAbtastwert;
int pufferGroesseInMillisekunden = 1000 * pufferGroesseInAnzahlAbtastwerten / recorder.getSampleRate();
// textViewPufferGroesseInAnzahlAbtastwerte.setText("" + pufferGroesseInAnzahlAbtastwerten);
// textViewPufferGroesseInMillisekunden.setText("" + pufferGroesseInMillisekunden);
}
@Override
@ -122,7 +178,7 @@ public class MicrophoneDetector extends Detector {
//Kalibrierung
try {
Thread.sleep(startDelay); // Time to lay down the phone
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
@ -132,27 +188,27 @@ public class MicrophoneDetector extends Detector {
Verarbeitungsergebnis kalibrierErgebnis = verarbeiten(puffer, n);
kalibierWert += kalibrierErgebnis.maxAmp;
try {
Thread.sleep(threadSleeptime);
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
kalibierWert = kalibierWert/i;
// __Part of FFT__
// Complex[] zeitSignal = new Complex[puffer.length];
// for (int j = 0; j < puffer.length; j++) {
// zeitSignal[j] = new Complex(puffer[j], 0);
// }
// Complex[] spektrum = FFT.fft(zeitSignal);
// double[] spektrum = calculateFFT(puffer);
// DataPoint AddPoint;
double[] spektrum = calculateFFT(puffer);
DataPoint AddPoint;
// LineGraphSeries<DataPoint> series = new LineGraphSeries<DataPoint>(new DataPoint[]{});
// for (i = 0; i < spektrum.length; i++) {
// AddPoint = new DataPoint(i, spektrum[i]);
// series.appendData(AddPoint, true, spektrum.length);
// }
// graph.addSeries(series);
// logger.log(spektrum.toString());
for (; ; ) {
if (aufnahmeTask.isCancelled()) {
@ -162,14 +218,14 @@ public class MicrophoneDetector extends Detector {
Verarbeitungsergebnis ergebnis = verarbeiten(puffer, n);
anzahlVerarbeitet += n;
// __Part of FFT__
// spektrum = calculateFFT(puffer);
// LineGraphSeries<DataPoint> newseries = new LineGraphSeries<DataPoint>(new DataPoint[]{});
// for (i = 0; i < spektrum.length; i++) {
// AddPoint = new DataPoint(i, spektrum[i]);
// newseries.appendData(AddPoint, true, spektrum.length);
// }
spektrum = calculateFFT(puffer);
LineGraphSeries<DataPoint> newseries = new LineGraphSeries<DataPoint>(new DataPoint[]{});
for (i = 0; i < spektrum.length; i++) {
AddPoint = new DataPoint(i, spektrum[i]);
newseries.appendData(AddPoint, true, spektrum.length);
}
graph.removeAllSeries();
graph.addSeries(newseries);
zaehlerZeitMessung++;
if (zaehlerZeitMessung == maxZaehlerZeitMessung) {
long time = System.currentTimeMillis();
@ -186,7 +242,7 @@ public class MicrophoneDetector extends Detector {
publishProgress(ergebnis);
try {
Thread.sleep(threadSleeptime);
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
@ -209,12 +265,13 @@ public class MicrophoneDetector extends Detector {
for (int i = 0; i < n; i++) {
if (daten[i] > max) {
max = daten[i];
//max = 20 * log10(abs(daten[i]) / 32768);
}
}
ringPuffer.hinzufuegen(max);
maxAmp = ringPuffer.maximum();
if (maxAmp <= schwellwertAlarm + kalibierWert) {
if (maxAmp <= Schwellwert_Alarm+kalibierWert) {
armed = true;
}
}
@ -225,16 +282,20 @@ public class MicrophoneDetector extends Detector {
@Override
protected void onProgressUpdate(Verarbeitungsergebnis... progress) {
super.onProgressUpdate(progress);
// textViewMaxAmp.setText("" + progress[0].maxAmp);
// textViewVerarbeitungsrate.setText("" + progress[0].verarbeitungsrate);
float maxAmpPrint = round(20*log10(abs(progress[0].maxAmp/1.0)));
float kalibierWertPrint = round(20*log10(abs(kalibierWert)));
Log.d("alarmAudio","VR: " + progress[0].verarbeitungsrate + ", Amp: " + maxAmpPrint
+ " dB, Kal: " + kalibierWertPrint + " dB");
logger.overwriteLastlog("VR, Max, Kal:" + progress[0].verarbeitungsrate + ", " + maxAmpPrint
+ " dB, " + kalibierWertPrint + " dB");
if (progress[0].maxAmp >= schwellwertAlarm + kalibierWert && armed == true) {
if (progress[0].maxAmp >= Schwellwert_Alarm+kalibierWert && armed == true) {
armed = false;
detectionReport = new DetectionReport(true, "Audio", maxAmpPrint);
reportViolation("Audio", maxAmpPrint);
Log.d("1",detectionReport.toString());
detectionReport = new DetectionReport("Mic1", "Audio", maxAmpPrint);
logger.log("");
logger.log("Alarm!");
logger.log(detectionReport.toString());
logger.log("");
}
}
}
@ -249,6 +310,7 @@ public class MicrophoneDetector extends Detector {
}
final int mNumberOfFFTPoints =1024;
double mMaxFFTSample;
double temp;
Complex[] y;
@ -262,9 +324,17 @@ public class MicrophoneDetector extends Detector {
y = FFT.fft(complexSignal);
mMaxFFTSample = 0.0;
// mPeakPos = 0;
for(int i = 0; i < (mNumberOfFFTPoints/2); i++)
{
absSignal[i] = y[i].abs();
// absSignal[i] = Math.sqrt(Math.pow(y[i].re(), 2) + Math.pow(y[i].im(), 2));
// if(absSignal[i] > mMaxFFTSample)
// {
// mMaxFFTSample = absSignal[i];
// // mPeakPos = i;
// }
}
return absSignal;
@ -352,6 +422,16 @@ public class MicrophoneDetector extends Detector {
this.wichtungAlterWert = 1 - this.wichtungNeuerWert;
}
float MittelwertPuffer(short[] puffer) {
for (int i = 0; i < puffer.length; i++) {
mittelwert = Math.abs(puffer[i]);
}
mittelwert = mittelwert/puffer.length;
return mittelwert;
}
float mittel(float wert) {
if (istMittelwertGesetzt) {
mittelwert = wert * wichtungNeuerWert + mittelwert * wichtungAlterWert;

View File

@ -1,43 +0,0 @@
package com.example.ueberwachungssystem;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class PermissionHandler {
private final Context context;
private static final int PERMISSION_REQUEST_CODE = 23409;
private static final String[] permissions = new String[]{
android.Manifest.permission.CAMERA,
android.Manifest.permission.RECORD_AUDIO
};
public PermissionHandler(Context context) {
this.context = context;
}
public boolean hasPermissions() {
boolean permissionState = true;
for (String permission: permissions) {
permissionState = permissionState && ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
}
return permissionState;
}
public void getPermissions() {
if (!hasPermissions())
ActivityCompat.requestPermissions((Activity) context, permissions, PERMISSION_REQUEST_CODE);
}
public void showPermissionToast() {
if (hasPermissions())
Toast.makeText(context, "permissions available", Toast.LENGTH_SHORT).show();
else
Toast.makeText(context, "permissions missing", Toast.LENGTH_SHORT).show();
}
}

View File

@ -1,48 +0,0 @@
package com.example.ueberwachungssystem;
import static android.Manifest.permission.INTERNET;
import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.RECORD_AUDIO;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
public class PermissionRequest extends AppCompatActivity{
private static final int PERMISSION_REQUEST_CODE = 123;
private final MainActivity mainActivity;
Handler handler = new Handler();
public PermissionRequest(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
public StringBuilder rechtePruefen() {
boolean rechtKamera = ContextCompat.checkSelfPermission(mainActivity, CAMERA) == PackageManager.PERMISSION_GRANTED;
boolean rechtMikrofon = ContextCompat.checkSelfPermission(mainActivity, RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
boolean rechtInternet = ContextCompat.checkSelfPermission(mainActivity, INTERNET) == PackageManager.PERMISSION_GRANTED;
StringBuilder sb = new StringBuilder();
sb.append("Rechte prüfen:")
.append("\nKamera: ").append(rechtKamera)
.append("\nMikrofon: ").append(rechtMikrofon)
.append("\nInternet: ").append(rechtInternet);
//mainActivity.runOnUiThread(() -> mainActivity.tvMessages.setText(sb));
if (!(rechtKamera && rechtMikrofon && rechtInternet)){
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(mainActivity.getApplicationContext(),"Es werden Rechte benötigt", Toast.LENGTH_SHORT).show();
}
});
}
return sb;
}
public void rechteAnfordern() {
mainActivity.requestPermissions(new String[]{CAMERA, RECORD_AUDIO, INTERNET}, PERMISSION_REQUEST_CODE);
}
}

View File

@ -1,96 +0,0 @@
package com.example.ueberwachungssystem;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
public class PopUpClass {
private final MainActivity mainActivity;
PermissionRequest permission;
TextView PopUpText;
Button buttonEdit;
public PopUpClass(MainActivity mainActivity) {
this.mainActivity = mainActivity;
permission = new PermissionRequest(mainActivity);
}
//PopupWindow display method
public void showPopupWindow(final View view) {
//Create a View object yourself through inflater
LayoutInflater inflater = (LayoutInflater) view.getContext().getSystemService(view.getContext().LAYOUT_INFLATER_SERVICE);
View popupView = inflater.inflate(R.layout.popup_window, null);
//Specify the length and width through constants
int width = LinearLayout.LayoutParams.WRAP_CONTENT;
int height = LinearLayout.LayoutParams.WRAP_CONTENT;
//Make Inactive Items Outside Of PopupWindow
boolean focusable = true;
//Create a window with our parameters
final PopupWindow popupWindow = new PopupWindow(popupView,width*1, height*1, focusable);
//Set the location of the window on the screen
popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
//Initialize the elements of our window, install the handler
PopUpText = popupView.findViewById(R.id.titleText);
buttonEdit = popupView.findViewById(R.id.RechteAnfordern);
buttonEdit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RechteAnfordern();
}
});
//Handler for clicking on the inactive zone of the window
popupView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
//Close the window when clicked
popupWindow.dismiss();
return true;
}
});
}
public void RechtePrüfen(){
StringBuilder Text = permission.rechtePruefen();
PopUpText.setText(Text);
buttonEdit.setVisibility(View.VISIBLE);
}
public void RechteAnfordern(){
permission.rechteAnfordern();
StringBuilder Text = permission.rechtePruefen();
PopUpText.setText(Text);
}
public void Sensoren(){
PopUpText.setText("Es können 3 verschiedene Sensoren verwendet werden \n -1. Beschleunigungssensor\n -2. Mikrofon\n -3. Kamera\n Diese können sowohl einzeln als auch alle zusammen verwendet werden");
buttonEdit.setVisibility(View.GONE);
}
public void Impressum(){
PopUpText.setText("Die Ueberwachungsapp wurde im Rahmen eines Praktikums der TH-Nürnberg programmiert \n Von: \n -Kohler Bastian\n -Kleinecke Oliver\n -Market Leon\n -Siebenhaar Miguel\n -Wolz Tobias ");
buttonEdit.setVisibility(View.GONE);
}
public void DetectionTotal(int num) {
PopUpText.setText("Total Detektions:" +num);
buttonEdit.setVisibility(View.GONE);
}
}

View File

@ -1,4 +1,4 @@
package com.example.ueberwachungssystem.Detection.Signalverarbeitung;
package com.example.ueberwachungssystem.Signalverarbeitung;
import java.util.Objects;
@ -12,7 +12,7 @@ public class Complex {
im = imag;
}
// return a string representation of the invoking com.example.ueberwachungssystem.Detection.Signalverarbeitung.Complex object
// return a string representation of the invoking com.example.ueberwachungssystem.Signalverarbeitung.Complex object
public String toString() {
if (im == 0) return re + "";
if (re == 0) return im + "i";
@ -30,7 +30,7 @@ public class Complex {
return Math.atan2(im, re);
}
// return a new com.example.ueberwachungssystem.Detection.Signalverarbeitung.Complex object whose value is (this + b)
// return a new com.example.ueberwachungssystem.Signalverarbeitung.Complex object whose value is (this + b)
public Complex plus(Complex b) {
Complex a = this; // invoking object
double real = a.re + b.re;
@ -38,7 +38,7 @@ public class Complex {
return new Complex(real, imag);
}
// return a new com.example.ueberwachungssystem.Detection.Signalverarbeitung.Complex object whose value is (this - b)
// return a new com.example.ueberwachungssystem.Signalverarbeitung.Complex object whose value is (this - b)
public Complex minus(Complex b) {
Complex a = this;
double real = a.re - b.re;
@ -46,7 +46,7 @@ public class Complex {
return new Complex(real, imag);
}
// return a new com.example.ueberwachungssystem.Detection.Signalverarbeitung.Complex object whose value is (this * b)
// return a new com.example.ueberwachungssystem.Signalverarbeitung.Complex object whose value is (this * b)
public Complex times(Complex b) {
Complex a = this;
double real = a.re * b.re - a.im * b.im;
@ -59,12 +59,12 @@ public class Complex {
return new Complex(alpha * re, alpha * im);
}
// return a new com.example.ueberwachungssystem.Detection.Signalverarbeitung.Complex object whose value is the conjugate of this
// return a new com.example.ueberwachungssystem.Signalverarbeitung.Complex object whose value is the conjugate of this
public Complex conjugate() {
return new Complex(re, -im);
}
// return a new com.example.ueberwachungssystem.Detection.Signalverarbeitung.Complex object whose value is the reciprocal of this
// return a new com.example.ueberwachungssystem.Signalverarbeitung.Complex object whose value is the reciprocal of this
public Complex reciprocal() {
double scale = re * re + im * im;
return new Complex(re / scale, -im / scale);
@ -85,22 +85,22 @@ public class Complex {
return a.times(b.reciprocal());
}
// return a new com.example.ueberwachungssystem.Detection.Signalverarbeitung.Complex object whose value is the complex exponential of this
// return a new com.example.ueberwachungssystem.Signalverarbeitung.Complex object whose value is the complex exponential of this
public Complex exp() {
return new Complex(Math.exp(re) * Math.cos(im), Math.exp(re) * Math.sin(im));
}
// return a new com.example.ueberwachungssystem.Detection.Signalverarbeitung.Complex object whose value is the complex sine of this
// return a new com.example.ueberwachungssystem.Signalverarbeitung.Complex object whose value is the complex sine of this
public Complex sin() {
return new Complex(Math.sin(re) * Math.cosh(im), Math.cos(re) * Math.sinh(im));
}
// return a new com.example.ueberwachungssystem.Detection.Signalverarbeitung.Complex object whose value is the complex cosine of this
// return a new com.example.ueberwachungssystem.Signalverarbeitung.Complex object whose value is the complex cosine of this
public Complex cos() {
return new Complex(Math.cos(re) * Math.cosh(im), -Math.sin(re) * Math.sinh(im));
}
// return a new com.example.ueberwachungssystem.Detection.Signalverarbeitung.Complex object whose value is the complex tangent of this
// return a new com.example.ueberwachungssystem.Signalverarbeitung.Complex object whose value is the complex tangent of this
public Complex tan() {
return sin().divides(cos());
}

View File

@ -1,10 +1,12 @@
package com.example.ueberwachungssystem.Detection.Signalverarbeitung;
package com.example.ueberwachungssystem.Signalverarbeitung;
// Source: https://introcs.cs.princeton.edu/java/97data/FFT.java.html
import android.util.Log;
/******************************************************************************
* Compilation: javac FFT.java
* Execution: java FFT n
* Dependencies: com.example.ueberwachungssystem.Detection.Signalverarbeitung.Complex.java
* Dependencies: com.example.ueberwachungssystem.Signalverarbeitung.Complex.java
*
* Compute the FFT and inverse FFT of a length n complex sequence
* using the radix 2 Cooley-Tukey algorithm.
@ -156,7 +158,7 @@ public class FFT {
return y;
}
// display an array of com.example.ueberwachungssystem.Detection.Signalverarbeitung.Complex numbers to standard output
// display an array of com.example.ueberwachungssystem.Signalverarbeitung.Complex numbers to standard output
public static void show(Complex[] x, String title) {
System.out.println(title);
System.out.println("-------------------");

View File

@ -1,176 +0,0 @@
package com.example.ueberwachungssystem;
import android.annotation.SuppressLint;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.example.ueberwachungssystem.Detection.DetectionReport;
import com.example.ueberwachungssystem.Detection.Detector;
import com.example.ueberwachungssystem.Detection.DetectorService;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
public class WifiCommunication {
//private final MainActivity mainActivity;
private final InetAddress address;
private final int port;
private String messageToSend;
volatile private boolean send;
private final DatagramSocket socket;
volatile private boolean running;
private boolean Gruppe =true;
private boolean showMessage = true;
StringBuffer rxStringBuffer = new StringBuffer();
private OnConnectionListener listener;
@SuppressLint("SetTextI18n")
public WifiCommunication(int port) {
//this.mainActivity = mainActivity;
this.port = port;
try {
socket = new DatagramSocket(this.port);
socket.setBroadcast(true);
address = InetAddress.getByName("255.255.255.255"); //100.82.255.255
running = true;
send = false;
new ReceiveThread().start();
new SendThread().start();
} catch (SocketException | UnknownHostException e) {
throw new RuntimeException(e);
}
//Toast.makeText(mainActivity.getApplicationContext(),"Communication running", Toast.LENGTH_SHORT).show();
//mainActivity.runOnUiThread(() -> mainActivity.tvMessages.setText("Communication running"));
}
public interface OnConnectionListener {
void onConnection(String data);
}
public void setOnConnectionListener(@NonNull OnConnectionListener listener) {
this.listener = listener;
}
public void sendWifiData(String wifiMessage) {
if (listener != null) {
listener.onConnection(wifiMessage);
}
}
private class ReceiveThread extends Thread {
private String rxString="";
private String previousRxString = "";
@Override
public void run() {
try {
do {
byte[] receiveData = new byte[512];
DatagramPacket rxPacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(rxPacket);
rxString = new String(receiveData, 0, rxPacket.getLength());
String[] splitrxString = rxString.split(",");
String[] splitrxStringBuffer = splitBufferIntoStrings(rxStringBuffer);
for(String elem: splitrxStringBuffer){
if(elem.equals(rxString)){
showMessage = false;
}else{
showMessage = true;
}
}
if(Gruppe){
if(!previousRxString.equals(rxString) && splitrxString[0].equals("1") && splitrxString.length==7 && showMessage) {
rxStringBuffer.append(rxString).append("\n");
Log.d("empfangen", rxString);
sendWifiData(rxString);
//mainActivity.runOnUiThread(() -> mainActivity.tvMessages.setText(rxStringBuffer));
previousRxString = rxString;
}
}else{
if(!previousRxString.equals(rxString) && splitrxString[0].equals("1") && splitrxString.length==7 && showMessage) {
rxStringBuffer.append(rxString).append("\n");
Log.d("empfangen", rxString);
sendWifiData(rxString);
//mainActivity.runOnUiThread(() -> mainActivity.tvMessages.setText(rxStringBuffer));
previousRxString = rxString;
}
}
} while (running);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
private class SendThread extends Thread {
private int tmpCnt = 0;
@Override
public void run() {
try {
do {
if(send)
{
send = false;
/*SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
Date curDate = new Date(System.currentTimeMillis());
String str = formatter.format(curDate);*/
byte[] send_Data = new byte[512];
String txString = (messageToSend); //"1," +str+ ",Gruppe2," + getLocalIpAddress() + ",An,Video,"
Log.d("send", txString);
send_Data = txString.getBytes();
DatagramPacket txPacket = new DatagramPacket(send_Data, txString.length(), address, port);
for(int i = 0; i < 500; i++) {
socket.send(txPacket);
}
}
} while (running);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface networkInterface = (NetworkInterface) ((Enumeration<?>) en).nextElement();
for (Enumeration<InetAddress> addresses = networkInterface.getInetAddresses(); addresses.hasMoreElements();) {
InetAddress inetAddress = addresses.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException ex) {
ex.printStackTrace();
}
return null;
}
public void sendTrue(String message){
send = true;
messageToSend = message;
}
public void stopCommunication() {
running = false;
socket.close();
}
public String[] splitBufferIntoStrings(StringBuffer string){
String[] splitrxString2 = string.toString().split("\n");
return splitrxString2;
}
}

View File

@ -0,0 +1,61 @@
package com.example.ueberwachungssystem.logger;
import android.util.Log;
import android.widget.TextView;
import java.io.PrintWriter;
import java.io.StringWriter;
public class Logger {
private TextView textView;
private StringBuffer sb = new StringBuffer();
private String tag;
private int lengthOfLastLog = 0;
private boolean overwrite = false;
public Logger(String tag, TextView textView, String logInitText) {
this.tag = tag;
this.textView = textView;
sb.append(logInitText);
}
public void log(String s) {
overwrite = false;
Log.d(tag, s);
sb.append(s).append("\n");
if (textView != null) {
textView.setText(sb.toString());
}
}
public void overwriteLastlog(String s) {
Log.d(tag, s);
lengthOfLastLog = s.length();
if (overwrite)
{
sb.setLength(sb.length() - (lengthOfLastLog + 1));
}
sb.append(s).append("\n");
overwrite = true;
if (textView != null) {
textView.setText(sb.toString());
}
}
public void log(Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log(sw.toString());
}
public void clearLog() {
sb.setLength(0);
if (textView != null) {
textView.setText("");
}
}
public String getLoggedText() {
return sb.toString();
}
}

View File

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false" android:drawable="@color/redbright" />
<item android:state_checked="true" android:drawable="@color/greenbright" />
</selector>

View File

@ -1,133 +1,56 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#010C49"
android:visibility="visible"
tools:context="com.example.ueberwachungssystem.MainActivity"
tools:visibility="visible">
android:layout_gravity="center"
android:gravity="top"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/textAuswahl"
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:textSize="20sp"
android:textColor="@color/white"/>
android:layout_height="100dp"
android:text="TextView" />
<TextView
android:id="@+id/textAoderA"
<androidx.camera.view.PreviewView
android:id="@+id/previewView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/toggleAudio"
android:layout_alignParentLeft="true"
android:layout_marginTop="15dp"
android:textSize="20sp"
android:textColor="@color/white"/>
android:backgroundTint="@android:color/black"/>
<ToggleButton
android:id="@+id/toggleKamera"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@id/toggleAudio"
android:layout_marginRight="30dp"
android:layout_toLeftOf="@id/toggleAudio"
android:textColor="@color/yellow"
android:textOn="Kamera an"
android:textOff="Kamera aus"
android:background="@drawable/toggle_btn"/>
<ToggleButton
android:id="@+id/toggleAudio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textAuswahl"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:textColor="@color/yellow"
android:textOn="Audio an"
android:textOff="Audio aus"
android:background="@drawable/toggle_btn"/>
<ToggleButton
android:id="@+id/toggleBewegung"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@id/toggleAudio"
android:layout_marginLeft="30dp"
android:layout_toEndOf="@+id/toggleAudio"
android:layout_toRightOf="@id/toggleAudio"
android:textColor="@color/yellow"
android:textOn="Bewegung an"
android:textOff="Bewegung aus"
android:background="@drawable/toggle_btn"/>
<Button
android:id="@+id/btnAlarme"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/btnAufnahmen"
android:layout_toLeftOf="@id/btnAufnahmen"
android:layout_marginRight="15dp"
android:theme="@style/Button.Green"
android:onClick="onClickZeigeFragment1"
android:text="Alarme" />
<Button
android:id="@+id/btnAufnahmen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textAoderA"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:theme="@style/Button.Green"
android:onClick="onClickZeigeFragment2"
android:text="Aufnahmen" />
<Button
android:id="@+id/btnAnzeigeVerb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/btnAufnahmen"
android:layout_toRightOf="@id/btnAufnahmen"
android:layout_marginLeft="15dp"
android:text="Live Video"
android:onClick="onClickZeigeFragment3"/>
<FrameLayout
android:id="@+id/frame"
android:id="@+id/toggleButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/btnAufnahmen"
android:layout_marginTop="25dp"
android:layout_alignParentStart="true"
android:background="@color/white">
</FrameLayout>
android:layout_height="wrap_content"
android:text="ToggleButton" />
<!--
<ScrollView
android:id="@+id/scrollView1"
<ImageView
android:id="@+id/inputImageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/btnAufnahmen"
android:layout_marginTop="25dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/Alarm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/red"/>
</LinearLayout>
</ScrollView>
-->
<ListView
android:id = "@+id/listView"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"/>
android:layout_height="wrap_content"
tools:srcCompat="@tools:sample/avatars" />
</RelativeLayout>
<ImageView
android:id="@+id/outputImageView"
android:layout_width="match_parent"
android:layout_height="1dp"
tools:srcCompat="@tools:sample/avatars" />
<com.jjoe64.graphview.GraphView
android:id="@+id/graph"
android:layout_width="match_parent"
android:layout_height="200dip"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.499" />
</LinearLayout>

View File

@ -1,26 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:background="@color/bluedark">
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="25dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/Alarm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/yellow"/>
</LinearLayout>
</ScrollView>
</RelativeLayout>

View File

@ -1,33 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:background="@android:color/holo_blue_light" >
<ScrollView
android:id="@+id/scrollView2"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_marginTop="25dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/Aufzeichnungen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/yellow"/>
</LinearLayout>
</ScrollView>
<VideoView
android:id="@+id/AusAuf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/scrollView2"
android:textAppearance="?android:attr/textAppearanceLarge"/>
</LinearLayout>

View File

@ -1,24 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:background="@color/bluedark">
<ImageView
android:id="@+id/Video"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:rotation="90">
</ImageView>
<ImageView
android:id="@+id/Video2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:rotation="90">
</ImageView>
</LinearLayout>

View File

@ -1,31 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:gravity="center"
android:background="#010C49">
<TextView
android:id="@+id/titleText"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="italic"
android:textColor="@color/white"
android:padding="10dp"/>
<Button
android:id="@+id/RechteAnfordern"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:backgroundTint="@color/purple_500"
android:text="Rechte Anfordern" />
</LinearLayout>

View File

@ -1,28 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:background="@android:color/holo_blue_light">
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Aufnahmen Löschen"
android:backgroundTint="#010C49"
tools:ignore="MissingConstraints" />
<ListView
android:id="@+id/listView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:ignore="MissingConstraints"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp" />
</androidx.appcompat.widget.LinearLayoutCompat>

View File

@ -1,12 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<VideoView
android:id="@+id/videoView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"/>
</FrameLayout>

View File

@ -1,11 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/Rechteverwaltung"
android:title="Rechteverwaltung" />
<item android:id="@+id/Sensoren"
android:title="Sensoren" />
<item android:id="@+id/Detection"
android:title="Detektionen" />
<item android:id="@+id/Impressum"
android:title="Impressum" />
</menu>

View File

@ -7,9 +7,4 @@
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
<color name="red">#5C0000</color>
<color name="redbright">#EF3434</color>
<color name="greenbright">#469733</color>
<color name="bluedark">#053C8E</color>
<color name="yellow">#FFEB3B</color>
</resources>

View File

@ -13,9 +13,4 @@
<item name="android:statusBarColor">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
</style>
<style name="Button.Green" parent="ThemeOverlay.AppCompat">
<item name="colorAccent">#0F3E01</item>
</style>
</resources>

View File

@ -1,5 +1,5 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
id 'com.android.application' version '8.0.0' apply false
id 'com.android.library' version '8.0.0' apply false
id 'com.android.application' version '7.4.2' apply false
id 'com.android.library' version '7.4.2' apply false
}

Binary file not shown.

View File

@ -19,5 +19,4 @@ android.useAndroidX=true
# resources declared in the library itself and none from the library's dependencies,
# thereby reducing the size of the R class for that library
android.nonTransitiveRClass=true
android.defaults.buildfeatures.buildconfig=true
android.nonFinalResIds=false
android.enableJetifier=true

View File

@ -1,6 +1,6 @@
#Thu May 11 15:19:24 CEST 2023
#Thu May 11 15:04:30 CEST 2023
distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME

View File

@ -14,4 +14,3 @@ dependencyResolutionManagement {
}
rootProject.name = "Ueberwachungssystem"
include ':app'
include ':app'