Compare commits

...

10 Commits

Author SHA1 Message Date
Leon Market
8a357e0d26 Fixed errors after merge with origin:lm 2023-06-17 19:20:32 +02:00
Leon Market
83268c763b Merge remote-tracking branch 'origin/lm' into lm
# Conflicts:
#	app/src/main/java/com/example/ueberwachungssystem/Beschleunigungssensor.java
2023-06-17 19:17:11 +02:00
Leon Market
3d02d8d4c0 Added 2023-06-17 19:16:48 +02:00
Leon Market
cafe763c4a Removed unnecessary code parts 2023-06-17 19:14:34 +02:00
Leon Market
2cff334056 Added detection report 2023-06-17 19:00:44 +02:00
Leon Market
6c4905d0e7 Added constructors for activity and textView in ThreadDemo 2023-06-15 14:27:25 +02:00
Leon Market
402b73e4bd Removed calibration code and added method checkAlarm 2023-06-14 22:28:05 +02:00
Leon Market
9e5b669986 Added Accelerometer as Runnable Class and ThreadDemo as example 2023-06-14 22:25:54 +02:00
Leon Market
8275d8bd5a Added 2023-06-14 22:11:17 +02:00
Leon Market
4999f1b998 added Detector, DetectorReport, Logger 2023-05-25 16:46:12 +02:00
13 changed files with 495 additions and 18 deletions

View File

3
Notiz.txt Normal file
View File

@ -0,0 +1,3 @@
Sensor als Service einrichten, der aus Activity heraus gestartet werden kann.
Stichwort: Intent
Siehe Skript Teil 1

View File

@ -0,0 +1,130 @@
package com.example.ueberwachungssystem;
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;
import android.widget.TextView;
public class Accelerometer extends Detector implements SensorEventListener {
Logger logger;
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;
TextView textViewLog;
// In constructor pass Activity, Context and TextView from MainActivity in Accelerometer class
public Accelerometer(Context context, Logger mainLogger, TextView textViewLog){
super(context); //von Detektor
logger = mainLogger;
this.context = context;
this.textViewLog = textViewLog;
//Logger logger = new Logger(this.getClass().getSimpleName(), textViewLog, "");
}
public void getSensor(){
sensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
if(sensorManager.getSensorList(sensorType).size()==0) {
logger.log("Es gibt den gewünschten Sensor nicht");
accelerometer = null;
}
else {
accelerometer = sensorManager.getSensorList(sensorType).get(0);
logger.log("Sensor gefunden");
}
}
void start() {
// register the sensor before using //
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
logger.log("Accelerometer, start!");
}
void stop() {
// unregister from the sensor to stop using it //
sensorManager.unregisterListener(this, accelerometer);
logger.log("Accelerometer unregistered!");
}
@Override
public void onSensorChanged(SensorEvent event) {
checkAlarm(event);
}
StringBuffer stringBuffer = new StringBuffer();
public void checkAlarm (SensorEvent event) {
x = event.values[0];
y = event.values[1];
z = event.values[2];
betrag = (float) sqrt(x*x + y*y + z*z);
double schwelle = 1.5;
if (!alarm) {
if (betrag > schwelle) {
stringBuffer.append("\n Betragswert über Schwelle, Detection Report wird gleich aufgerufen");
//logger.log("Betragswert über Schwelle erkannt, Alarm wird gleich angeschaltet");
alarm = true;
stringBuffer.append("\nAlarm = " + alarm);
detectionReport = new DetectionReport("Accelerometer1", "Bewegung", betrag);
stringBuffer.append("\nDetectionReport = " + detectionReport)
.append("\nAlarm an" + betrag + event.timestamp);
//logger.log("Alarm an");
//logger.log("Betrag: " + betrag + event.timestamp);
logger.clearLog();
logger.log(stringBuffer.toString());
stringBuffer.delete(0, stringBuffer.length());
}
} else {
if (betrag < schwelle) {
stringBuffer.append("\nAlarm noch an; Neuer Betragswert unter Schwellwert:" + betrag);
//logger.log("Alarm ist noch an; Neuer Betragswert unter Schwellwert: " + betrag);
alarm = false;
//logger.log("Alarm" + alarm);
//logger.log("Alarm wieder ausgeschaltet");
stringBuffer.append("\nAlarm = " + alarm);
} else {
logger.log("Betragswert immer noch über Schwellwert: " + betrag + "; Alarm bleibt an.");
logger.log("Betragswert immer noch über Schwellwert: " + betrag + "; Alarm bleibt an.");
}
//logger.clearLog();
logger.log(stringBuffer.toString());
stringBuffer.delete(0, stringBuffer.length());
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void startDetection() {
// entspricht void start()
if (accelerometer != null) {
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);
logger.log("Sensor registriert");
}
}
@Override
public void stopDetection() {
// entspricht void stop()
sensorManager.unregisterListener(this, accelerometer);
logger.log("Vom Sensor abgemeldet");
}
}

View File

@ -1,22 +1,39 @@
package com.example.ueberwachungssystem;
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;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.TextView;
import com.example.ueberwachungssystem.Logger;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collection;
import java.util.Deque;
import java.util.Iterator;
import java.util.OptionalDouble;
import java.util.Queue;
public class Beschleunigungssensor extends AppCompatActivity implements SensorEventListener
{
private Logger logger;
private SensorManager sensorManager;
private int sensorType = Sensor.TYPE_ACCELEROMETER;
private static final int sensorType = Sensor.TYPE_LINEAR_ACCELERATION;
private Sensor sensor;
boolean alarm = false;
//Preallocate memory for the data of each axis of the acceleration sensor
double x;
double y;
double z;
double betrag; //Betrag aller drei Achsen sqrt(x*x + y*y + z*z)
@Override
protected void onCreate(Bundle savedInstanceState)
@ -37,6 +54,7 @@ public class Beschleunigungssensor extends AppCompatActivity implements SensorEv
else
{
sensor = sensorManager.getSensorList(sensorType).get(0);
logger.log("Accelerometer gefunden.");
}
}
@ -46,7 +64,7 @@ public class Beschleunigungssensor extends AppCompatActivity implements SensorEv
super.onResume();
if(sensor != null)
{
if(sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME))
if(sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL))
{
logger.log("Wir haben uns beim Sensor angemeldet.");
}
@ -67,20 +85,39 @@ public class Beschleunigungssensor extends AppCompatActivity implements SensorEv
}
}
private void checkAlarm (SensorEvent event) {
x = event.values[0];
y = event.values[1];
z = event.values[2];
betrag = sqrt(x*x + y*y + z*z);
double schwelle = 0.05;
if (!alarm) {
if (betrag > schwelle) {
logger.log("Betragswert über Schwelle erkannt, Alarm wird gleich angeschaltet");
alarm = true;
logger.log("Alarm an");
logger.log("Betrag: " + betrag + event.timestamp);
}
} else {
if (betrag < schwelle) {
logger.log("Alarm ist noch an; Neuer Betragswert unter Schwellwert: " + betrag);
alarm = false;
logger.log("Alarm wieder ausgeschaltet");
} else {
logger.log("Betragswert immer noch über Schwellwert: " + betrag + "; Alarm bleibt an.");
}
}
}
@Override
public void onSensorChanged(SensorEvent event)
{
StringBuilder sb = new StringBuilder();
sb.append("t=").append(event.timestamp)
.append("\nx=").append(event.values[0])
.append("\ny=").append(event.values[1])
.append("\nz=").append(event.values[2]);
logger.clearLog();
logger.log(sb.toString());
checkAlarm(event);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
}
}

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,39 @@
package com.example.ueberwachungssystem;
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

@ -0,0 +1,44 @@
package com.example.ueberwachungssystem;
import android.widget.TextView;
import android.util.Log;
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();
}
}

View File

@ -1,14 +1,85 @@
package com.example.ueberwachungssystem;
import static java.lang.Boolean.TRUE;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.hardware.SensorEvent;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity {
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Logger logger;
private Context context;
private Accelerometer beschleunigungssensor;
//private ThreadDemo threadDemo;
private TextView textViewLog;
private Button button1;
private TextView textViewWorkerThread;
SensorEvent event;
ToggleButton toggleButton1;
boolean currentAlarm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(this.getClass().getSimpleName());
setContentView(R.layout.activity_main);
// Logger setup
textViewLog = (TextView) findViewById(R.id.textViewLog);
logger = new Logger(this.getClass().getSimpleName(), textViewLog, "");
toggleButton1 = (ToggleButton) findViewById(R.id.toggleButton1); //togglebutton um Thread zu steuern
toggleButton1.setOnClickListener(this);
textViewWorkerThread = (TextView) findViewById(R.id.textViewWorkerThread); //TextView um Thread zu überwachen
textViewWorkerThread.setMovementMethod(new ScrollingMovementMethod());
//Button to clear Log while Debugging
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);
//Accelerometer Setup
beschleunigungssensor = new Accelerometer(this, logger, textViewWorkerThread);
beschleunigungssensor.getSensor();
logger.log("onCreate");
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
beschleunigungssensor.stopDetection();
}
@Override
public void onClick(View v) {
logger.log("toggleButton1 is clicked");
if(v == toggleButton1) {
if (toggleButton1.isChecked()) {
logger.log("ToggleButton is ON");
beschleunigungssensor.startDetection();
logger.log("Detection started");
} else {
logger.log("ToggleButton is OFF");
beschleunigungssensor.stopDetection();
logger.log("Detection stopped");
}
} else if (v == button1) {
logger.clearLog();
}
}
}

View File

@ -0,0 +1,70 @@
package com.example.ueberwachungssystem;
import android.content.Context;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class ThreadDemo implements Runnable {
private volatile boolean running = false;
private Thread thread;
private String threadname = "testThread";
Logger logger;
// Passing Activity's instance as argument on worker thread
AppCompatActivity activity;
public ThreadDemo(AppCompatActivity activity){
this.activity = activity;
}
//Method print which delegates access on MainActivity to runOnUiThread
private void print(final String s) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
//textViewWorkerThread.setText(s);
}
});
}
@Override
public void run() {
int i = 0;
while (running) {
i++;
print(String.valueOf(i));
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//print(activity.getString(R.string.workerThread) + " endet mit " + i);
}
void start() {
logger.log("Starting " + threadname + "...");
running = true;
thread = new Thread(this);
thread.setName(threadname);
thread.start();
logger.log("..." + threadname + " started");
}
void stop() {
if (!running) {
logger.log(threadname + " not running");
} else {
logger.log("Stopping " + threadname + "...");
running = false;
while(true){
try {
thread.join();
logger.log("... " + threadname + " stopped");
break;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

View File

@ -7,12 +7,57 @@
tools:context=".MainActivity">
<TextView
android:id="@+id/textViewLog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:layout_marginStart="32dp"
android:layout_marginTop="60dp"
android:layout_marginEnd="32dp"
android:maxLines="25"
android:scrollbars="vertical"
android:text="TextViewLoggerMain"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textViewWorkerThread"
app:layout_constraintVertical_bias="0.0" />
<ToggleButton
android:id="@+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="161dp"
android:layout_marginTop="115dp"
android:layout_marginEnd="162dp"
android:text="ToggleButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textViewWorkerThread"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="32dp"
android:text="textViewWorkerThreadTextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/toggleButton1" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="35dp"
android:layout_marginTop="31dp"
android:layout_marginEnd="282dp"
android:layout_marginBottom="100dp"
android:text="Clear Log"
app:layout_constraintBottom_toTopOf="@+id/textViewWorkerThread"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

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 '7.4.2' apply false
id 'com.android.library' version '7.4.2' apply false
id 'com.android.application' version '8.0.0' apply false
id 'com.android.library' version '8.0.0' apply false
}

View File

@ -18,4 +18,6 @@ android.useAndroidX=true
# Enables namespacing of each library's R class so that its R class includes only the
# 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.nonTransitiveRClass=true
android.defaults.buildfeatures.buildconfig=true
android.nonFinalResIds=false

View File

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