Compare commits

...
14 Commits
14 changed files with 633 additions and 6 deletions

No files matched your search

View File
Whitespace-only changes.
+3
View File
@@ -0,0 +1,3 @@
Sensor als Service einrichten, der aus Activity heraus gestartet werden kann.
Stichwort: Intent
Siehe Skript Teil 1
@@ -0,0 +1,139 @@
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;
import java.util.concurrent.LinkedBlockingQueue;
/**
* 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 {
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 textView;
//Queue for taking in values
LinkedBlockingQueue<Float> linkedBlockingQueue = new LinkedBlockingQueue<>();
// In constructor pass Activity, Context and TextView from MainActivity in Accelerometer class
public Accelerometer(Context context, Logger mainLogger, TextView textView){
super(context); //von Detektor
logger = mainLogger;
this.context = context;
this.textView = this.textView;
//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");
}
}
@Override
public void onSensorChanged(SensorEvent event) {
try {
checkAlarm(event);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
StringBuffer stringBuffer = new StringBuffer();
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;
detectionReport = new DetectionReport("Accelerometer1", "Bewegung", betrag);
stringBuffer.append("\nDetectionReport = ").append(detectionReport).append("\nAlarm an");
logger.clearLog();
logger.log(stringBuffer.toString());
stringBuffer.delete(0, stringBuffer.length());
}
} else {
if (betrag < threshold) {
stringBuffer.append("\nAlarm noch an; Neuer Betragswert unter Schwellwert:").append(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 = ").append(alarm);
} else {
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");
}
}
@@ -0,0 +1,123 @@
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 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 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)
{
super.onCreate(savedInstanceState);
setTitle(this.getClass().getSimpleName());
TextView textView = new TextView(this);
setContentView(textView);
logger = new Logger(this.getClass().getSimpleName(),textView,"");
sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
if(sensorManager.getSensorList(sensorType).size()==0)
{
logger.log("Es gibt den gewünschten Sensor nicht");
sensor = null;
}
else
{
sensor = sensorManager.getSensorList(sensorType).get(0);
logger.log("Accelerometer gefunden.");
}
}
@Override
protected void onResume()
{
super.onResume();
if(sensor != null)
{
if(sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL))
{
logger.log("Wir haben uns beim Sensor angemeldet.");
}
else
{
logger.log("Das Anmelden beim Sensor hat nicht so gut geklappt");
}
}
}
@Override
protected void onPause()
{
super.onPause();
if(sensor != null) {
sensorManager.unregisterListener(this, sensor);
logger.log("Wir haben uns beim Sensor abgemeldet");
}
}
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)
{
checkAlarm(event);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
}
@@ -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());
}
}
@@ -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();
}
@@ -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();
}
}
@@ -1,14 +1,77 @@
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 Accelerometer beschleunigungssensor;
private TextView textViewLog;
private Button button1;
ToggleButton toggleButton1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(this.getClass().getSimpleName());
setContentView(R.layout.activity_main);
// Logger setup
textViewLog = findViewById(R.id.textViewLog);
textViewLog.setMovementMethod(new ScrollingMovementMethod());
logger = new Logger(this.getClass().getSimpleName(), textViewLog, "");
toggleButton1 = findViewById(R.id.toggleButton1); //togglebutton um Detektion zu steuern
toggleButton1.setOnClickListener(this);
//Button to clear Log while Debugging
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);
//Accelerometer Setup
beschleunigungssensor = new Accelerometer(this, logger, textViewLog); //logger and textview only for debugging necessary
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(); //just to clear log manually if it's too full
}
}
}
@@ -0,0 +1,63 @@
package com.example.ueberwachungssystem;
import androidx.appcompat.app.AppCompatActivity;
import java.util.concurrent.LinkedBlockingQueue;
public class SensorValueThread implements Runnable {
private volatile boolean running = false;
private Thread thread;
private String threadname = "sensorValueThread";
Logger logger;
float x;
LinkedBlockingQueue<Float> linkedBlockingQueue;
//AppCompatActivity activity;
//Constructor muss die LinkedBlockingQueue übergeben bekommen
public SensorValueThread(LinkedBlockingQueue linkedBlockingQueue){
this.linkedBlockingQueue = linkedBlockingQueue;
}
@Override
public void run() {
while (running){
//Code to execute while running == true, i.e. reading queue and calculate sth.
try {
x = linkedBlockingQueue.take();
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
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();
}
}
}
}
}
@@ -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();
}
}
}
}
}
+46 -1
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>
+2 -2
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
}
+3 -1
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
+1 -1
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