Compare commits

..
10 Commits
Author SHA1 Message Date
kleineckeol72024 44e056b5fe Merge branch 'ko'
# Conflicts:
#	app/src/main/java/com/example/ueberwachungssystem/MainActivity.java
2023-06-15 17:06:56 +02:00
kleineckeol72024 df1fefef5f added Toggle Button to start Cam Detection 2023-06-15 16:59:17 +02:00
kleineckeol72024 5bcd465ecc Merge branch 'master' into ko
# Conflicts:
#	app/build.gradle
#	app/src/main/AndroidManifest.xml
#	app/src/main/res/layout/activity_main.xml
#	gradle/wrapper/gradle-wrapper.properties
2023-06-15 16:20:40 +02:00
kleineckeol72024 a6fdf3f774 added landscape xml file 2023-06-15 16:12:30 +02:00
kleineckeol72024 b46db4cdfc reworked Button Positions 2023-06-15 16:04:50 +02:00
kleineckeol72024 74eb3e0d98 Added Toggle Buttons for Detection Mode
Added Scrollview for alarm
2023-06-12 20:23:42 +02:00
kleineckeol72024 5f7e2a43f2 added new Project ueberwachungssystem 2023-06-12 19:04:22 +02:00
kleineckeol72024 07f60f974b added new Project ueberwachungssystem 2023-06-12 14:15:39 +02:00
kleineckeol72024 57bf2c2fb7 added new Project ueberwachungssystem 2023-05-11 15:31:47 +02:00
kleineckeol72024 5c0263198c added new Project ueberwachungssystem 2023-05-11 15:25:28 +02:00
23 changed files with 575 additions and 1036 deletions
-12
View File
@@ -26,9 +26,6 @@ android {
sourceCompatibility JavaVersion.VERSION_1_8 sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8
} }
buildFeatures {
viewBinding true
}
} }
dependencies { dependencies {
@@ -36,19 +33,10 @@ dependencies {
implementation 'androidx.appcompat:appcompat:1.6.1' implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.8.0' implementation 'com.google.android.material:material:1.8.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4' implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'com.google.android.gms:play-services-nearby:18.0.0'
testImplementation 'junit:junit:4.13.2' testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5' androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
// OpenCV (from: https://github.com/QuickBirdEng/opencv-android)
def opencv_version = "4.5.3.0"
implementation "com.quickbirdstudios:opencv:${opencv_version}"
implementation "androidx.lifecycle:lifecycle-extensions:2.0.0"
// Required for CameraX // Required for CameraX
def camerax_version = "1.2.2" def camerax_version = "1.2.2"
implementation "androidx.camera:camera-core:${camerax_version}" implementation "androidx.camera:camera-core:${camerax_version}"
+21 -4
View File
@@ -2,9 +2,27 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"> xmlns:tools="http://schemas.android.com/tools">
<uses-feature android:name="android.hardware.camera"/> <!-- &lt;!&ndash; If your app targets Android 13 (API level 33)-->
<uses-permission android:name="android.permission.CAMERA"/> <!-- or higher, you must declare the NEARBY_WIFI_DEVICES permission. &ndash;&gt;-->
<uses-permission android:name="android.permission.RECORD_AUDIO" /> <!-- <uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES"-->
<!-- &lt;!&ndash; If your app derives location information from Wi-Fi APIs,-->
<!-- don't include the "usesPermissionFlags" attribute. &ndash;&gt;-->
<!-- android:usesPermissionFlags="neverForLocation" />-->
<uses-permission
android:required="true"
android:name="android.permission.ACCESS_FINE_LOCATION"/>
<!-- If any feature in your app relies on precise location information,
don't include the "maxSdkVersion" attribute. -->
<uses-permission
android:required="true"
android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission
android:required="true"
android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission
android:required="true"
android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
@@ -28,7 +46,6 @@
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </intent-filter>
</activity> </activity>
<service android:name=".Detection.DetectorService"/>
</application> </application>
</manifest> </manifest>
@@ -1,74 +0,0 @@
package com.example.ueberwachungssystem.Detection;
import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class AudioRecorder {
private final Context context;
private MediaRecorder mediaRecorder = null;
private boolean isRecording = false;
private File outputDir; // Default: in app files directory
public AudioRecorder (Context context) {
this.context = context;
this.outputDir = context.getFilesDir();
}
public void startRecording() {
// Handle logic
if (outputDir == null)
return;
if (isRecording)
return;
isRecording = true;
// Setup Audio Recorder for output Format: 3GP
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setOutputFile(outputDir + "/" + generateFileName() + ".3gp");
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mediaRecorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaRecorder.start();
}
public void stopRecording() {
if (mediaRecorder != null) {
mediaRecorder.stop();
mediaRecorder.reset();
mediaRecorder.release();
mediaRecorder = null;
isRecording = false;
Toast.makeText(context, "audio recording saved", Toast.LENGTH_SHORT).show();
}
}
public boolean isRecording(){
return isRecording;
}
public void setOutputDir(File outputDir) {
this.outputDir = outputDir;
}
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);
}
}
@@ -9,26 +9,24 @@ public class DetectionReport {
public String timeStamp; public String timeStamp;
public String detectionType; public String detectionType;
public float detectedValue; public float detectedValue;
public boolean detectionState; public String detectorID;
public DetectionReport(boolean detectionState, String detectionType, float detectedAmplitude) { public DetectionReport(String detectorID, String detectionType, float detectedAmplitude) {
this.timeStamp = String.valueOf(Calendar.getInstance().getTime()); this.timeStamp = String.valueOf(Calendar.getInstance().getTime());
this.detectionType = detectionType; this.detectionType = detectionType;
this.detectedValue = detectedAmplitude; this.detectedValue = detectedAmplitude;
this.detectionState = detectionState; this.detectorID = detectorID;
//this.detectorID = detectorID;
} }
/** Get Detection Report in String format */ /** Get Detection Report in String format */
public String toString() { public String toString() {
String state = "State: " + "[" + this.detectionState + "]";
String time = "Time: " + "[" + this.timeStamp + "]"; String time = "Time: " + "[" + this.timeStamp + "]";
String type = "Type: " + "[" + this.detectionType + "]"; String type = "Type: " + "[" + this.detectionType + "]";
String value = "Value: " + "[" + this.detectedValue + "]"; String value = "Value: " + "[" + this.detectedValue + "]";
String id = "ID: " + "[" + this.detectorID + "]";
return String.join("\t", state, time, type, value); return String.join("\t", time, type, value, id);
} }
/** Debug Report */ /** Debug Report */
@@ -1,19 +1,10 @@
package com.example.ueberwachungssystem.Detection; package com.example.ueberwachungssystem.Detection;
import android.os.CountDownTimer;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.camera.core.ExperimentalGetImage;
abstract public class Detector { abstract public class Detector {
private OnDetectionListener listener; private OnDetectionListener listener;
private boolean isDetecting = false;
private boolean extendViolation = false;
// Countdown parameters
private final int COUNTDOWN_TIME = 10000; // milliseconds
private final int COUNTDOWN_POLLING_TIME = 100; // milliseconds
/** Constructor - takes context of current activity */ /** Constructor - takes context of current activity */
public Detector() {} public Detector() {}
@@ -27,46 +18,17 @@ abstract public class Detector {
this.listener = listener; this.listener = listener;
} }
/** Triggers onDetectionListener - call this to trigger violation/alarm */ /** Triggers onDetectionListener - call this to trigger violation/alarm */
public void reportViolation(String detectionType, float amplitude) { public void reportViolation(String detectorID, String detectionType, float amplitude) {
if (listener != null) { if (listener != null) {
if (!isDetecting) { DetectionReport detectionReport = new DetectionReport(detectorID, detectionType, amplitude);
isDetecting = true; listener.onDetection(detectionReport);
DetectionReport detectionReport = new DetectionReport(true, detectionType, amplitude);
listener.onDetection(detectionReport);
startDetectionTimer(detectionType, amplitude);
} else {
extendViolation = true;
}
} else { } else {
isDetecting = false; throw new IllegalStateException("No listener set for violation reporting");
extendViolation = false;
} }
} }
private void startDetectionTimer(String detectionType, float amplitude) {
isDetecting = true;
new CountDownTimer((long) COUNTDOWN_TIME, COUNTDOWN_POLLING_TIME) {
@Override
public void onTick(long millisUntilFinished) {
if (extendViolation) {
extendViolation = false;
startDetectionTimer(detectionType, amplitude);
this.cancel();
}
}
@Override
public void onFinish() {
isDetecting = false;
DetectionReport detectionReport = new DetectionReport(false, detectionType, amplitude);
listener.onDetection(detectionReport);
}
}.start();
}
public void extendViolation(){
this.extendViolation = true;
}
/** Starts Detection (abstract method: needs to be overridden in child class) */ /** Starts Detection (abstract method: needs to be overridden in child class) */
public abstract void startDetection(); public abstract void startDetection();
@@ -1,174 +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 android.widget.Toast;
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;
VideoDetector videoDetector = null;
AudioRecorder audioRecorder = null;
/** Communication **/
WifiCommunication wifiCommunication;
StringBuffer dataFromWifi;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (isServiceRunning)
return START_NOT_STICKY;
// Setup Service classes:
videoDetector = new VideoDetector(this);
videoDetector.setOnDetectionListener(new Detector.OnDetectionListener() {
@Override
public void onDetection(@NonNull DetectionReport detectionReport) {
passToServiceListener(detectionReport);
}
});
audioRecorder = new AudioRecorder(this);
isServiceRunning = true;
wifiCommunication = new WifiCommunication (1234);
wifiCommunication.setOnConnectionListener(new WifiCommunication.OnConnectionListener() {
@Override
public void onConnection(StringBuffer data) {
dataFromWifi = data;
}
});
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;
}
/** Video Detection */
public void startVideoDetection() {
if(videoDetector != null)
videoDetector.startDetection();
}
public void stopVideoDetection() {
if(videoDetector != null)
videoDetector.stopDetection();
}
public boolean isVideoDetectionRunning() {
if(videoDetector != null)
return videoDetector.isDetecting();
return false;
}
public void debugVideoProcessing(ImageView input, ImageView output) {
if(videoDetector != null)
videoDetector.debugProcessing(input, output);
}
/** Audio Detection */
public void startAudioDetection() {
}
public void stopAudioDetection() {
}
/** Motion Detection */
public void startMotionDetection() {
}
public void stopMotionDetection() {
}
/** Video Recording */
public void startVideoRecording() {
if(videoDetector != null)
videoDetector.startRecording();
}
public void stopVideoRecording() {
if(videoDetector != null)
videoDetector.stopRecording();
}
public boolean isVideoRecordingRunning() {
if(videoDetector != null)
return videoDetector.isRecording();
return false;
}
public void setVideoRecordingDir(File outputDir) {
if (videoDetector != null)
videoDetector.setOutputDir(outputDir);
}
/** Audio Recording */
public void startAudioRecording() {
if(audioRecorder != null)
audioRecorder.startRecording();
}
public void stopAudioRecording() {
if(audioRecorder != null)
audioRecorder.stopRecording();
}
public boolean isAudioRecordingRunning() {
if(videoDetector != null)
return audioRecorder.isRecording();
return false;
}
public void setAudioRecordingDir(File outputDir) {
if (audioRecorder != null)
audioRecorder.setOutputDir(outputDir);
}
/** pass Detection Report to Service Detection Listener and trigger it */
public void passToServiceListener(DetectionReport detectionReport) {
if (listener != null) {
listener.onDetection(detectionReport);
}
}
/** On Detection Listener - runs when violation is reported */
public interface OnDetectionListener {
void onDetection(@NonNull DetectionReport detectionReport);
}
public void setOnDetectionListener(@NonNull DetectorService.OnDetectionListener listener) {
this.listener = listener;
}
}
@@ -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);
}
}
@@ -1,327 +1,196 @@
package com.example.ueberwachungssystem.Detection; package com.example.ueberwachungssystem.Detection;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context; import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.ImageFormat; import android.graphics.ImageFormat;
import android.media.Image; import android.media.Image;
import android.os.CountDownTimer; import android.util.Size;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.camera.core.CameraSelector; import androidx.camera.core.CameraSelector;
import androidx.camera.core.ExperimentalGetImage; import androidx.camera.core.ExperimentalGetImage;
import androidx.camera.core.ImageAnalysis; import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview; import androidx.camera.core.Preview;
import androidx.camera.core.VideoCapture;
import androidx.camera.lifecycle.ProcessCameraProvider; import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView; import androidx.camera.view.PreviewView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat; import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.LifecycleOwner;
import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListenableFuture;
import org.opencv.android.OpenCVLoader; import java.nio.ByteBuffer;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
/** /**
* Video Detector inherits some methods from abstract Detector class (more info there) * Video Detector inherits some methods from abstract Detector class (more info there)
*
*
* USE FROM MAIN ACTIVITY: * USE FROM MAIN ACTIVITY:
*
* VideoDetector vd = new VideoDetector(this); * VideoDetector vd = new VideoDetector(this);
* vd.setPreview(previewView); //THIS IS OPTIONAL!
* vd.setOnDetectionListener(new Detector.OnDetectionListener{...});
* vd.startDetection();
* vd.stopDetection
*
* */ * */
@ExperimentalGetImage @ExperimentalGetImage
public class VideoDetector extends Detector { public class VideoDetector extends Detector {
// Calling Activity // Calling Activity
private final Context context; private final Context context;
// Camera Provider // Camera Provider
private ProcessCameraProvider cameraProvider; private ProcessCameraProvider cameraProvider;
private ImageAnalysis imageAnalysis; private Boolean isDetectionRunning = false;
private VideoCapture videoCapture; // Preview Camera Image
//private Preview preview; private PreviewView previewView = null;
// Detect Violation
// Logic private static final float PIXEL_THRESHOLD = 30f; // Luminosity (brightness channel of YUV_420_888)
private boolean isDetecting = false; private static final float ALARM_THRESHOLD = 0.2f; // Percent of pixels changed
private boolean isRecording = false; private ByteBuffer previousBuffer = null;
private boolean allowReportViolation = false;
// Image Processing
private Mat previousImage = null;
// Debugging
private ImageView inputImageView = null;
private ImageView outputImageView = null;
// Recorder
private File outputDir; // Default: in app files directory
// 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 = 20000; // milliseconds
private static final android.util.Size IMAGE_RES = new android.util.Size(640, 480);
/** Constructor */ /**
* Constructor
* @param context: the context of calling activity (usually "this")
* */
public VideoDetector(Context context) { public VideoDetector(Context context) {
super(); super();
this.context = context; this.context = context;
this.imageAnalysis = setupImageAnalysis();
this.videoCapture = setupVideoCapture();
this.outputDir = context.getFilesDir();
//this.preview = new Preview.Builder().build();
}
/** Get States */
public boolean isDetecting() {
return isDetecting;
}
public boolean isRecording(){
return isRecording;
} }
/** Starts the Video Detection */ /**
* Starts the Video Detection
* */
@Override @Override
public void startDetection() { public void startDetection() {
// Check States if (isDetectionRunning)
if (isDetecting)
return; return;
// Configure Image Analysis // Request Camera Provider
imageAnalysis = setupImageAnalysis();
// Open CV startup check
if (!OpenCVLoader.initDebug()) {
Log.e("OpenCV", "Unable to load OpenCV!");
return;
} else
Log.d("OpenCV", "OpenCV loaded Successfully!");
// Get Process Camera Provider and start
final ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(context); final ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(context);
//Check for Camera availability
cameraProviderFuture.addListener(() -> { cameraProviderFuture.addListener(() -> {
try { try {
cameraProvider = cameraProviderFuture.get(); cameraProvider = cameraProviderFuture.get();
isDetecting = true; bindAnalysis(cameraProvider);
bindCameraProvider(); isDetectionRunning = true;
} catch (ExecutionException | InterruptedException e) {} previousBuffer = null;
}, ContextCompat.getMainExecutor(context)); } catch (ExecutionException | InterruptedException e) {
// Disable Violation Calling for Setup Time // No errors need to be handled for this Future. This should never be reached.
startViolationTimer(START_DELAY); }
},ContextCompat.getMainExecutor(context));
} }
/** Starts the Recorder */
@SuppressLint("RestrictedApi")
public void startRecording() {
// Check States
if (isRecording){
return;
}
videoCapture = setupVideoCapture(); /**
* Stops the Video Detection
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, "video recording saved", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(int videoCaptureError, @NonNull String message, @Nullable Throwable cause) {
isRecording = false;
Toast.makeText(context, "video recording failed", Toast.LENGTH_SHORT).show();
}
}
);
} catch (ExecutionException | InterruptedException ignored) {}
}, ContextCompat.getMainExecutor(context));
}
/** Stops the Video Detection */
@Override @Override
public void stopDetection() { public void stopDetection() {
if (!isDetecting || imageAnalysis == null) if (!isDetectionRunning)
return; return;
cameraProvider.unbind(imageAnalysis);
isDetecting = false;
allowReportViolation = false;
}
/** Stops the Recording */
@SuppressLint("RestrictedApi")
public void stopRecording(){
if(!isRecording)
return;
videoCapture.stopRecording();
cameraProvider.unbind(videoCapture);
isRecording = false;
}
/** Bind Camera Provider */
private void bindCameraProvider() {
// Specify which Camera to use
CameraSelector cameraSelector = new CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build();
cameraProvider.unbindAll(); cameraProvider.unbindAll();
cameraProvider.bindToLifecycle((LifecycleOwner) context, cameraSelector, imageAnalysis, videoCapture); isDetectionRunning = false;
} }
/** Setup Use Cases */
private ImageAnalysis setupImageAnalysis() { /**
* Set PreviewView to show video feed while detecting
* this is optional and does not need to be called
* */
public void setPreviewView(PreviewView previewView) {
this.previewView = previewView;
}
/**
* Binds the Luminosity Analyzer (configure and run Analysis)
* @param cameraProvider: CameraProvider of Context passed by Constructor
* */
private void bindAnalysis(@NonNull ProcessCameraProvider cameraProvider) {
// Configure and create Image Analysis // Configure and create Image Analysis
ImageAnalysis.Builder builder = new ImageAnalysis.Builder(); ImageAnalysis.Builder builder = new ImageAnalysis.Builder();
builder.setTargetResolution(IMAGE_RES); builder.setTargetResolution(new Size(640, 480));
builder.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST); builder.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST);
builder.setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888); builder.setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888);
builder.setTargetRotation(Surface.ROTATION_90);
ImageAnalysis imageAnalysis = builder.build(); ImageAnalysis imageAnalysis = builder.build();
// Set Analyzer // Set Analyzer
imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(context), imageProxy -> { imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(context), imageProxy -> {
if (imageProxy.getFormat() == ImageFormat.YUV_420_888) { if (imageProxy.getFormat() == ImageFormat.YUV_420_888) {
Image image = imageProxy.getImage(); Image image = imageProxy.getImage();
assert image != null; assert image != null;
// Violation Handling // Changed Pixel Detection
Mat processed = processImage(imageProxy); int pixelChanged = getChangedPixelCount(image);
int width = image.getWidth();
int height = image.getHeight();
int n = OpenCVHelper.countNonZeroPixels(processed); float percentPixelChanged = (float) 100f * pixelChanged / (width * height);
int pixelCount = image.getWidth() * image.getHeight();
float percentChanged = (float) n / pixelCount;
// Violation Condition if (percentPixelChanged > ALARM_THRESHOLD)
if (percentChanged * 100 > ALARM_THRESHOLD) { reportViolation("0", "Video", percentPixelChanged);
if (allowReportViolation)
reportViolation("Video", percentChanged);
}
} }
imageProxy.close(); imageProxy.close();
}); });
return imageAnalysis; // Create Preview
} Preview preview = new Preview.Builder().build();
// Specify which Camera to use
CameraSelector cameraSelector = new CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build();
// Update PreviewView if set
if (previewView != null)
preview.setSurfaceProvider(previewView.getSurfaceProvider());
@SuppressLint("RestrictedApi") cameraProvider.bindToLifecycle((LifecycleOwner) context, cameraSelector, imageAnalysis, preview);
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) { * Calculate Amount of Pixels changed using a threshold
// Create Preview * @param image
if (this.preview != null) * */
this.preview.setSurfaceProvider(previewView.getSurfaceProvider()); private int getChangedPixelCount(Image image) {
} Image.Plane[] planes = image.getPlanes();
*/ ByteBuffer buffer = planes[0].getBuffer();
if (previousBuffer == null) {
previousBuffer = ByteBuffer.allocate(buffer.capacity());
buffer.rewind();
previousBuffer.put(buffer);
previousBuffer.rewind();
return 0;
}
/** Generate File Name */ int width = image.getWidth();
private String generateFileName(){ int height = image.getHeight();
// 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);
}
int yRowStride = image.getPlanes()[0].getRowStride();
int yPixelStride = image.getPlanes()[0].getPixelStride();
/** Get current Display Rotation */ int changedPixelCount = 0;
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 */ // Count changed pixels
private void startViolationTimer(float setupTime) { for (int y = 0; y < height; ++y) {
new CountDownTimer((long) (START_DELAY), 100) { for (int x = 0; x < width; x++) {
@Override int index = (y * yRowStride) + (x * yPixelStride);
public void onTick(long millisUntilFinished) { int luminosity = (buffer.get(index) & 0xff);
int previousLuminosity = (previousBuffer.get(index) & 0xff);
int diff = Math.abs(luminosity - previousLuminosity);
if (diff > PIXEL_THRESHOLD)
changedPixelCount++;
} }
@Override }
public void onFinish() {
allowReportViolation = true;
}
}.start();
}
public void setOutputDir(File outputDir) { // Reset and copy Byte Buffer
this.outputDir = outputDir; buffer.rewind();
previousBuffer.rewind();
previousBuffer.put(buffer);
return changedPixelCount;
} }
} }
@@ -0,0 +1,44 @@
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;
public Logger(String tag, TextView textView, String logInitText) {
this.tag = tag;
this.textView = textView;
sb.append(logInitText);
}
public void log(String s) {
Log.d(tag, s);
sb.append(s).append("\n");
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();
}
}
@@ -1,113 +1,220 @@
package com.example.ueberwachungssystem; package com.example.ueberwachungssystem;
import static android.content.ContentValues.TAG; import androidx.annotation.NonNull;
import androidx.camera.core.ExperimentalGetImage;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle; import android.os.Bundle;
import android.util.Log; import android.util.Log;
import android.view.MenuItem; import android.view.LayoutInflater;
import android.widget.Toast;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View; import android.view.View;
import android.view.ViewGroup;
import android.widget.Button; import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.ToggleButton;
import androidx.appcompat.app.AppCompatActivity; import com.example.ueberwachungssystem.Detection.DetectionReport;
import java.net.InetAddress; import com.example.ueberwachungssystem.Detection.Detector;
import java.net.UnknownHostException; import com.example.ueberwachungssystem.Detection.VideoDetector;
import java.nio.ByteBuffer; import org.w3c.dom.Text;
import java.nio.ByteOrder;
@SuppressLint("SetTextI18n")
public class MainActivity extends AppCompatActivity {
@ExperimentalGetImage
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Fragment aktuellesFragment;
WifiCommunication communication; WifiCommunication communication;
PermissionRequest permission; private TextView alarm;
boolean communicationRunning = true; private String text = "Das ist ein Alarm des Sensors";
String dataRecieved; //Buttons
TextView textview1; private ToggleButton toggleKamera;
private ToggleButton btnAudio;
private ToggleButton btnBewegung;
//Detektoren
VideoDetector vd = new VideoDetector(this);
private void log(String nachricht) {
Log.d(this.getClass().getSimpleName(), nachricht);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview1 = findViewById(R.id.textView1);
Button button1 = findViewById(R.id.buttonSend);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
communication.sendTrue("Testmessage");
}
});
}
@Override @Override
protected void onResume() { protected void onCreate(Bundle savedInstanceState) {
super.onResume(); super.onCreate(savedInstanceState);
if (communicationRunning){ setTitle(this.getClass().getSimpleName());
communication = new WifiCommunication(1234); setContentView(R.layout.activity_main);
communication.setOnConnectionListener(new WifiCommunication.OnConnectionListener() { alarm = findViewById(R.id.Alarm);
@Override alarm.setText(text);
public void onConnection(StringBuffer data) { toggleKamera = findViewById(R.id.toggleKamera);
//Log.d("Test", data.toString()); toggleKamera.setOnClickListener(this);
runOnUiThread(new Runnable() { vd.setOnDetectionListener(new Detector.OnDetectionListener() {
@Override @Override
public void run() { public void onDetection(@NonNull DetectionReport detectionReport) {
textview1.setText(data); DetectionReport dr = detectionReport;
} String drString = dr.toString();
}); }
} });
});
communicationRunning = false; //boolean isRunning = vd.isRunning();
}
permission = new PermissionRequest(MainActivity.this); }
permission.rechtePruefen(); @Override
public void onClick(View v) {
if (v == toggleKamera) {
if (toggleKamera.isChecked()) {
vd.startDetection();
} else {
vd.stopDetection();
}
} }
}
@Override @Override
protected void onPause() { protected void onPause() {
super.onPause(); super.onPause();
//communication.stopCommunication(); communication.stopCommunication();
} }
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.options_menu, menu); @Override
return true; protected void onResume() {
super.onResume();
communication = new WifiCommunication(MainActivity.this, 1234);
} }
public boolean onOptionsItemSelected(MenuItem item) {
Toast.makeText(this, "Selected Item: " + item.getTitle(), Toast.LENGTH_SHORT).show(); public void onClickZeigeFragment1(View view) {
PopUpClass popUpClass; Button button = (Button) view;
switch (item.getItemId()) { log(button.getText() + " ausgewählt");
case R.id.Rechteverwaltung: zeigeFragment(Fragment1.erstellen("Fragment 1 wurde angeklickt"));
popUpClass = new PopUpClass(MainActivity.this); }
//popUpClass.showPopupWindow(tvMessages); public void onClickZeigeFragment2(View view) {
popUpClass.RechtePrüfen(); Button button = (Button) view;
return true; log(button.getText() + " ausgewählt");
case R.id.Sensoren: zeigeFragment(Fragment2.erstellen("Fragment 2 wurde angeklickt"));
popUpClass = new PopUpClass(MainActivity.this); }
//popUpClass.showPopupWindow(tvMessages);
popUpClass.Sensoren(); public void onClickZeigeFragment3(View view) {
return true; Button button = (Button) view;
case R.id.Impressum: log(button.getText() + " ausgewählt");
popUpClass = new PopUpClass(MainActivity.this); zeigeFragment(Fragment3.erstellen("Fragment 3 wurde angeklickt"));
//popUpClass.showPopupWindow(tvMessages); }
popUpClass.Impressum();
return true; public void onClickEntferneFragment(View view) {
default: entferneFragment();
return super.onOptionsItemSelected(item); }
private void zeigeFragment(Fragment fragment) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.frame, fragment);
ft.commit();
aktuellesFragment = fragment;
}
private void entferneFragment() {
if (aktuellesFragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.remove(aktuellesFragment);
ft.commit();
aktuellesFragment = null ;
} }
} }
private String getLocalIpAddress() throws UnknownHostException { public static class Fragment1 extends Fragment {
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); private String text;
assert wifiManager != null; private final static String KEY_TEXT = "KEY_TEXT";
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipInt = wifiInfo.getIpAddress();
return InetAddress.getByAddress(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(ipInt).array()).getHostAddress();
}
}
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.Sensor);
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;
}
@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");
}
}
}
public static class Fragment2 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.fragment2, container, false );
TextView Sensor = (TextView) view.findViewById(R.id.Sensor);
Sensor.setText(text);
return view;
}
public static Fragment2 erstellen(String text) {
Fragment2 fragment = new Fragment2();
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");
}
}
}
public static class Fragment3 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.fragment2, container, false );
TextView Sensor = (TextView) view.findViewById(R.id.Sensor);
Sensor.setText(text);
return view;
}
public static Fragment3 erstellen(String text) {
Fragment3 fragment = new Fragment3();
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");
}
}
}
}
@@ -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();
}
}
@@ -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_LONG).show();
}
});
}
return sb;
}
public void rechteAnfordern() {
mainActivity.requestPermissions(new String[]{CAMERA, RECORD_AUDIO, INTERNET}, PERMISSION_REQUEST_CODE);
}
}
@@ -1,86 +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;
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);
Button 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);
}
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");
}
public void Impressum(){
PopUpText.setText("Die Ueberwachungsapp wurde im Rahmen eines Praktikums der TH-Nürnberg programmiert");
}
}
@@ -1,12 +1,5 @@
package com.example.ueberwachungssystem; package com.example.ueberwachungssystem;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
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.io.IOException;
import java.net.DatagramPacket; import java.net.DatagramPacket;
@@ -21,7 +14,7 @@ import java.util.Date;
import java.util.Enumeration; import java.util.Enumeration;
public class WifiCommunication { public class WifiCommunication {
//private final MainActivity mainActivity; private final MainActivity mainActivity;
private final InetAddress address; private final InetAddress address;
private final int port; private final int port;
@@ -29,11 +22,9 @@ public class WifiCommunication {
volatile private boolean send; volatile private boolean send;
private final DatagramSocket socket; private final DatagramSocket socket;
volatile private boolean running; volatile private boolean running;
private OnConnectionListener listener;
@SuppressLint("SetTextI18n") @SuppressLint("SetTextI18n")
public WifiCommunication(int port) { public WifiCommunication(MainActivity mainActivity, int port) {
//this.mainActivity = mainActivity; this.mainActivity = mainActivity;
this.port = port; this.port = port;
try { try {
socket = new DatagramSocket(this.port); socket = new DatagramSocket(this.port);
@@ -46,23 +37,8 @@ public class WifiCommunication {
} catch (SocketException | UnknownHostException e) { } catch (SocketException | UnknownHostException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
//Toast.makeText(mainActivity.getApplicationContext(),"Communication running", Toast.LENGTH_SHORT).show();
//mainActivity.runOnUiThread(() -> mainActivity.tvMessages.setText("Communication running")); //mainActivity.runOnUiThread(() -> mainActivity.tvMessages.setText("Communication running"));
} }
public interface OnConnectionListener {
void onConnection(StringBuffer data);
}
public void setOnConnectionListener(@NonNull OnConnectionListener listener) {
this.listener = listener;
}
public void sendWifiData(StringBuffer wifiMessage) {
if (listener != null) {
listener.onConnection(wifiMessage);
}
}
private class ReceiveThread extends Thread { private class ReceiveThread extends Thread {
private StringBuffer rxStringBuffer = new StringBuffer(); private StringBuffer rxStringBuffer = new StringBuffer();
private String rxString=""; private String rxString="";
@@ -73,16 +49,20 @@ public class WifiCommunication {
try { try {
do { do {
byte[] receiveData = new byte[512]; byte[] receiveData = new byte[512];
InetAddress fromAdress;
int fromPort;
DatagramPacket rxPacket = new DatagramPacket(receiveData, receiveData.length); DatagramPacket rxPacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(rxPacket); socket.receive(rxPacket);
rxString = new String(receiveData, 0, rxPacket.getLength()); fromAdress = rxPacket.getAddress();
String[] splitrxString = rxString.split(","); fromPort = rxPacket.getPort();
if(!previousRxString.equals(rxString) && splitrxString[0].equals("1") && splitrxString.length==7) { rxString = new String(rxPacket.getData());
if(!previousRxString.equals(rxString)) {
rxStringBuffer.append(rxString).append("\n"); rxStringBuffer.append(rxString).append("\n");
sendWifiData(rxStringBuffer);
//mainActivity.runOnUiThread(() -> mainActivity.tvMessages.setText(rxStringBuffer)); //mainActivity.runOnUiThread(() -> mainActivity.tvMessages.setText(rxStringBuffer));
previousRxString = rxString; previousRxString = rxString;
} }
} while (running); } while (running);
} }
catch (IOException e) { catch (IOException e) {
@@ -103,13 +83,18 @@ public class WifiCommunication {
Date curDate = new Date(System.currentTimeMillis()); Date curDate = new Date(System.currentTimeMillis());
String str = formatter.format(curDate); String str = formatter.format(curDate);
byte[] send_Data = new byte[512]; byte[] send_Data = new byte[512];
String txString = ("1," +str+ ",Gruppe2," + getLocalIpAddress() + ",An,Video," +messageToSend); String txString = (str+ ",Gruppe2," + getLocalIpAddress() + ",An,Video," +messageToSend);
send_Data = txString.getBytes(); send_Data = txString.getBytes();
DatagramPacket txPacket = new DatagramPacket(send_Data, txString.length(), address, port); DatagramPacket txPacket = new DatagramPacket(send_Data, txString.length(), address, port);
for(int i = 0; i < 300; i++) { for(int i = 0; i < 500; i++) {
socket.send(txPacket); socket.send(txPacket);
/*try{
sleep(10);
}catch (InterruptedException e){
e.printStackTrace();
}*/
} }
} }
} while (running); } while (running);
@@ -0,0 +1,6 @@
<?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">
</LinearLayout>
+105 -35
View File
@@ -1,53 +1,123 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" <RelativeLayout 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" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
android:layout_gravity="center" android:background="@android:color/holo_green_dark"
android:gravity="top" android:visibility="visible"
android:orientation="vertical" tools:context="com.example.ueberwachungssystem.MainActivity"
tools:context=".MainActivity"> tools:visibility="visible">
<androidx.camera.view.PreviewView
android:id="@+id/previewView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="@android:color/black"/>
<ToggleButton <ToggleButton
android:id="@+id/toggleButton" android:id="@+id/toggleKamera"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="ToggleButton" />
<ImageView
android:id="@+id/inputImageView"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
tools:srcCompat="@tools:sample/avatars" /> android:layout_alignBottom="@id/toggleAudio"
android:layout_marginRight="15dp"
android:layout_toStartOf="@+id/toggleAudio"
android:layout_toLeftOf="@id/toggleAudio"
android:text="Kamera" />
<ImageView <ToggleButton
android:id="@+id/outputImageView" android:id="@+id/toggleAudio"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
tools:srcCompat="@tools:sample/avatars" /> android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Audio" />
<androidx.camera.view.PreviewView <ToggleButton
android:id="@+id/toggleBewegung"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:text="TextView" /> android:layout_alignBottom="@id/toggleAudio"
android:layout_marginLeft="15dp"
android:layout_toEndOf="@+id/toggleAudio"
android:layout_toRightOf="@id/toggleAudio"
android:text="Bewegung" />
<Button <Button
android:id="@+id/buttonSend" android:id="@+id/btnAudio"
android:layout_width="match_parent" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:text="Button" /> android:layout_alignBottom="@id/btnKamera"
android:layout_marginRight="15dp"
android:layout_toStartOf="@+id/btnKamera"
android:onClick="onClickZeigeFragment1"
android:text="Audio" />
</LinearLayout> <Button
android:id="@+id/btnKamera"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/toggleAudio"
android:layout_centerHorizontal="true"
android:onClick="onClickZeigeFragment2"
android:text="Kamera" />
<!--
<Button
android:id="@+id/btnSensorWeg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="@+id/btn1"
android:text="Entferne Sensordarstellung"
android:onClick="onClickEntferneFragment"/>
-->
<Button
android:id="@+id/btnBewegung"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@id/btnKamera"
android:layout_marginLeft="15dp"
android:layout_toEndOf="@+id/btnKamera"
android:layout_toRightOf="@id/btnKamera"
android:onClick="onClickZeigeFragment3"
android:text="Bewegung" />
<Button
android:id="@+id/btnAufnahme"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btnKamera"
android:layout_toLeftOf="@id/btnKamera"
android:layout_marginRight="15dp"
android:onClick="onClickEntferneFragment"
android:text="Aufnahme" />
<Button
android:id="@+id/btnWiedergabe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btnKamera"
android:layout_toRightOf="@id/btnKamera"
android:layout_marginLeft="15dp"
android:onClick="onClickEntferneFragment"
android:text="Wiedergabe" />
<FrameLayout
android:id="@+id/frame"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_below="@+id/btnAufnahme"
android:layout_alignParentStart="true">
</FrameLayout>
<ScrollView
android:id= "@+id/scrollView1"
android:layout_width= "wrap_content"
android:layout_height= "wrap_content"
android:layout_below= "@id/frame">
<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" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
+22
View File
@@ -0,0 +1,22 @@
<?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="@android:color/holo_green_light">
<TextView
android:id="@+id/Sensor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"/>
<TextView
android:id="@+id/Alarm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/Sensor"
android:textAppearance="?android:attr/textAppearanceLarge"/>
</RelativeLayout>
+22
View File
@@ -0,0 +1,22 @@
<?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" >
<TextView
android:id="@+id/Sensor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"/>
<TextView
android:id="@+id/Alarm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/Sensor"
android:textAppearance="?android:attr/textAppearanceLarge"/>
</LinearLayout>
+22
View File
@@ -0,0 +1,22 @@
<?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" >
<TextView
android:id="@+id/Sensor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"/>
<TextView
android:id="@+id/Alarm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/Sensor"
android:textAppearance="?android:attr/textAppearanceLarge"/>
</LinearLayout>
-29
View File
@@ -1,29 +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="#A5ACB2">
<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:padding="10dp"/>
<Button
android:id="@+id/RechteAnfordern"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Rechte Anfordern" />
</LinearLayout>
-9
View File
@@ -1,9 +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/Impressum"
android:title="Impressum" />
</menu>
+1 -1
View File
@@ -1,4 +1,4 @@
#Thu May 11 15:04:30 CEST 2023 #Thu May 11 15:19:24 CEST 2023
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip
distributionPath=wrapper/dists distributionPath=wrapper/dists
-1
View File
@@ -14,4 +14,3 @@ dependencyResolutionManagement {
} }
rootProject.name = "Ueberwachungssystem" rootProject.name = "Ueberwachungssystem"
include ':app' include ':app'
include ':app'