Compare commits

...
3 Commits
8 changed files with 61 additions and 156 deletions
@@ -1,4 +1,4 @@
package com.example.ueberwachungssystem;
package com.example.ueberwachungssystem.Detector;
import android.util.Log;
@@ -1,6 +1,5 @@
package com.example.ueberwachungssystem;
package com.example.ueberwachungssystem.Detector;
import android.app.Activity;
import android.content.Context;
import androidx.annotation.NonNull;
@@ -22,7 +21,7 @@ abstract public class Detector {
/** Triggers onDetectionListener - call this to trigger violation/alarm */
private void reportViolation(String detectorID, String detectionType, float amplitude) {
public void reportViolation(String detectorID, String detectionType, float amplitude) {
if (listener != null) {
DetectionReport detectionReport = new DetectionReport(detectorID, detectionType, amplitude);
listener.onDetection(detectionReport);
@@ -1,4 +1,4 @@
package com.example.ueberwachungssystem;
package com.example.ueberwachungssystem.Detector;
import static java.lang.Math.*;
@@ -10,13 +10,14 @@ import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.AsyncTask;
import android.util.Log;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.example.ueberwachungssystem.Signalverarbeitung.Complex;
import com.example.ueberwachungssystem.Signalverarbeitung.FFT;
import com.example.ueberwachungssystem.logger.Logger;
import com.example.ueberwachungssystem.Detector.Signalverarbeitung.Complex;
import com.example.ueberwachungssystem.Detector.Signalverarbeitung.FFT;
import com.example.ueberwachungssystem.Detector.logger.Logger;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
@@ -33,17 +34,11 @@ public class MicrophoneDetector extends Detector {
private AufnahmeTask aufnahmeTask;
public boolean armed = false;
public int Schwellwert_Alarm = 100;
GraphView graph;
Logger logger;
private Activity MainActivityForClass;
public MicrophoneDetector(Context context, Logger MainLogger, GraphView MainGraph) {
public MicrophoneDetector(Context context) {
super(context);
MainActivityForClass = (Activity) context;
logger = MainLogger; //Class uses the same logger as the MainActivity
logger.log(this.getClass().getSimpleName() + ".onCreate");
graph = MainGraph;
if (!istZugriffAufMikrofonErlaubt()) {
zugriffAufMikrofonAnfordern();
@@ -52,7 +47,6 @@ public class MicrophoneDetector extends Detector {
@Override
public void startDetection() {
logger.log(this.getClass().getSimpleName() + ".startDetection");
if (!istZugriffAufMikrofonErlaubt()) {
zugriffAufMikrofonAnfordern();
@@ -65,19 +59,17 @@ public class MicrophoneDetector extends Detector {
@Override
public void stopDetection() {
logger.log(this.getClass().getSimpleName() + ".stopDetection");
if (aufnahmeTask != null) {
aufnahmeTask.cancel(true);
// aufnahmeTask = null; // if aufnahmeTask = null, break in for loop would not work (Nullpointer Exception)
}
}
private boolean istZugriffAufMikrofonErlaubt() {
if (ContextCompat.checkSelfPermission(MainActivityForClass, android.Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
logger.log("Zugriff auf Mikrofon ist verboten.");
Log.d("0","Zugriff auf Mikrofon ist verboten.");
return false;
} else {
logger.log("Zugriff auf Mikrofon ist erlaubt.");
Log.d("0","Zugriff auf Mikrofon ist erlaubt.");
return true;
}
}
@@ -113,13 +105,8 @@ public class MicrophoneDetector extends Detector {
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRateInHz, channelConfig, audioFormat, pufferGroesseInBytes);
// textViewMinPufferGroesseInBytes.setText("" + minPufferGroesseInBytes);
// textViewPufferGroesseInBytes.setText("" + pufferGroesseInBytes);
// textViewAbtastrate.setText("" + recorder.getSampleRate());
// textViewAnzahlKanaele.setText("" + recorder.getChannelCount());
logger.log("Puffergroeße: "+ minPufferGroesseInBytes + " " + pufferGroesseInBytes);
logger.log("Recorder (SR, CH): "+ recorder.getSampleRate() + " " + recorder.getChannelCount());
Log.d("0","Puffergroeße: "+ minPufferGroesseInBytes + " " + pufferGroesseInBytes);
Log.d("0","Recorder (SR, CH): "+ recorder.getSampleRate() + " " + recorder.getChannelCount());
int anzahlBytesProAbtastwert;
String s;
@@ -139,7 +126,6 @@ public class MicrophoneDetector extends Detector {
default:
throw new IllegalArgumentException();
}
// textViewAudioFormat.setText(s);
switch (recorder.getChannelConfiguration()) {
case AudioFormat.CHANNEL_IN_MONO:
@@ -155,14 +141,12 @@ public class MicrophoneDetector extends Detector {
default:
throw new IllegalArgumentException();
}
// textViewKanalKonfiguration.setText(s);
logger.log("Konfiguration: "+ s);
Log.d("0","Konfiguration: "+ s);
int pufferGroesseInAnzahlAbtastwerten = pufferGroesseInBytes / anzahlBytesProAbtastwert;
int pufferGroesseInMillisekunden = 1000 * pufferGroesseInAnzahlAbtastwerten / recorder.getSampleRate();
// textViewPufferGroesseInAnzahlAbtastwerte.setText("" + pufferGroesseInAnzahlAbtastwerten);
// textViewPufferGroesseInMillisekunden.setText("" + pufferGroesseInMillisekunden);
}
@Override
@@ -178,7 +162,7 @@ public class MicrophoneDetector extends Detector {
//Kalibrierung
try {
Thread.sleep(3000);
Thread.sleep(3000); // Time to lay down the phone
} catch (InterruptedException e) {
e.printStackTrace();
}
@@ -195,20 +179,20 @@ public class MicrophoneDetector extends Detector {
}
kalibierWert = kalibierWert/i;
// __Part of FFT__
// Complex[] zeitSignal = new Complex[puffer.length];
// for (int j = 0; j < puffer.length; j++) {
// zeitSignal[j] = new Complex(puffer[j], 0);
// }
// Complex[] spektrum = FFT.fft(zeitSignal);
double[] spektrum = calculateFFT(puffer);
DataPoint AddPoint;
// double[] spektrum = calculateFFT(puffer);
// DataPoint AddPoint;
// LineGraphSeries<DataPoint> series = new LineGraphSeries<DataPoint>(new DataPoint[]{});
// for (i = 0; i < spektrum.length; i++) {
// AddPoint = new DataPoint(i, spektrum[i]);
// series.appendData(AddPoint, true, spektrum.length);
// }
// graph.addSeries(series);
// logger.log(spektrum.toString());
for (; ; ) {
if (aufnahmeTask.isCancelled()) {
@@ -217,15 +201,14 @@ public class MicrophoneDetector extends Detector {
int n = recorder.read(puffer, 0, puffer.length);
Verarbeitungsergebnis ergebnis = verarbeiten(puffer, n);
anzahlVerarbeitet += n;
// __Part of FFT__
// spektrum = calculateFFT(puffer);
// LineGraphSeries<DataPoint> newseries = new LineGraphSeries<DataPoint>(new DataPoint[]{});
// for (i = 0; i < spektrum.length; i++) {
// AddPoint = new DataPoint(i, spektrum[i]);
// newseries.appendData(AddPoint, true, spektrum.length);
// }
spektrum = calculateFFT(puffer);
LineGraphSeries<DataPoint> newseries = new LineGraphSeries<DataPoint>(new DataPoint[]{});
for (i = 0; i < spektrum.length; i++) {
AddPoint = new DataPoint(i, spektrum[i]);
newseries.appendData(AddPoint, true, spektrum.length);
}
graph.removeAllSeries();
graph.addSeries(newseries);
zaehlerZeitMessung++;
if (zaehlerZeitMessung == maxZaehlerZeitMessung) {
long time = System.currentTimeMillis();
@@ -242,7 +225,7 @@ public class MicrophoneDetector extends Detector {
publishProgress(ergebnis);
try {
Thread.sleep(100);
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
@@ -265,7 +248,6 @@ public class MicrophoneDetector extends Detector {
for (int i = 0; i < n; i++) {
if (daten[i] > max) {
max = daten[i];
//max = 20 * log10(abs(daten[i]) / 32768);
}
}
@@ -282,20 +264,16 @@ public class MicrophoneDetector extends Detector {
@Override
protected void onProgressUpdate(Verarbeitungsergebnis... progress) {
super.onProgressUpdate(progress);
// textViewMaxAmp.setText("" + progress[0].maxAmp);
// textViewVerarbeitungsrate.setText("" + progress[0].verarbeitungsrate);
float maxAmpPrint = round(20*log10(abs(progress[0].maxAmp/1.0)));
float kalibierWertPrint = round(20*log10(abs(kalibierWert)));
logger.overwriteLastlog("VR, Max, Kal:" + progress[0].verarbeitungsrate + ", " + maxAmpPrint
Log.d("0","VR, Max, Kal:" + progress[0].verarbeitungsrate + ", " + maxAmpPrint
+ " dB, " + kalibierWertPrint + " dB");
if (progress[0].maxAmp >= Schwellwert_Alarm+kalibierWert && armed == true) {
armed = false;
detectionReport = new DetectionReport("Mic1", "Audio", maxAmpPrint);
logger.log("");
logger.log("Alarm!");
logger.log(detectionReport.toString());
logger.log("");
reportViolation("Mic1", "Audio", maxAmpPrint);
Log.d("1",detectionReport.toString());
}
}
}
@@ -325,7 +303,6 @@ public class MicrophoneDetector extends Detector {
y = FFT.fft(complexSignal);
mMaxFFTSample = 0.0;
// mPeakPos = 0;
for(int i = 0; i < (mNumberOfFFTPoints/2); i++)
{
absSignal[i] = y[i].abs();
@@ -333,7 +310,6 @@ public class MicrophoneDetector extends Detector {
// if(absSignal[i] > mMaxFFTSample)
// {
// mMaxFFTSample = absSignal[i];
// // mPeakPos = i;
// }
}
@@ -1,4 +1,4 @@
package com.example.ueberwachungssystem.Signalverarbeitung;
package com.example.ueberwachungssystem.Detector.Signalverarbeitung;
import java.util.Objects;
@@ -12,7 +12,7 @@ public class Complex {
im = imag;
}
// return a string representation of the invoking com.example.ueberwachungssystem.Signalverarbeitung.Complex object
// return a string representation of the invoking com.example.ueberwachungssystem.Detector.Signalverarbeitung.Complex object
public String toString() {
if (im == 0) return re + "";
if (re == 0) return im + "i";
@@ -30,7 +30,7 @@ public class Complex {
return Math.atan2(im, re);
}
// return a new com.example.ueberwachungssystem.Signalverarbeitung.Complex object whose value is (this + b)
// return a new com.example.ueberwachungssystem.Detector.Signalverarbeitung.Complex object whose value is (this + b)
public Complex plus(Complex b) {
Complex a = this; // invoking object
double real = a.re + b.re;
@@ -38,7 +38,7 @@ public class Complex {
return new Complex(real, imag);
}
// return a new com.example.ueberwachungssystem.Signalverarbeitung.Complex object whose value is (this - b)
// return a new com.example.ueberwachungssystem.Detector.Signalverarbeitung.Complex object whose value is (this - b)
public Complex minus(Complex b) {
Complex a = this;
double real = a.re - b.re;
@@ -46,7 +46,7 @@ public class Complex {
return new Complex(real, imag);
}
// return a new com.example.ueberwachungssystem.Signalverarbeitung.Complex object whose value is (this * b)
// return a new com.example.ueberwachungssystem.Detector.Signalverarbeitung.Complex object whose value is (this * b)
public Complex times(Complex b) {
Complex a = this;
double real = a.re * b.re - a.im * b.im;
@@ -59,12 +59,12 @@ public class Complex {
return new Complex(alpha * re, alpha * im);
}
// return a new com.example.ueberwachungssystem.Signalverarbeitung.Complex object whose value is the conjugate of this
// return a new com.example.ueberwachungssystem.Detector.Signalverarbeitung.Complex object whose value is the conjugate of this
public Complex conjugate() {
return new Complex(re, -im);
}
// return a new com.example.ueberwachungssystem.Signalverarbeitung.Complex object whose value is the reciprocal of this
// return a new com.example.ueberwachungssystem.Detector.Signalverarbeitung.Complex object whose value is the reciprocal of this
public Complex reciprocal() {
double scale = re * re + im * im;
return new Complex(re / scale, -im / scale);
@@ -85,22 +85,22 @@ public class Complex {
return a.times(b.reciprocal());
}
// return a new com.example.ueberwachungssystem.Signalverarbeitung.Complex object whose value is the complex exponential of this
// return a new com.example.ueberwachungssystem.Detector.Signalverarbeitung.Complex object whose value is the complex exponential of this
public Complex exp() {
return new Complex(Math.exp(re) * Math.cos(im), Math.exp(re) * Math.sin(im));
}
// return a new com.example.ueberwachungssystem.Signalverarbeitung.Complex object whose value is the complex sine of this
// return a new com.example.ueberwachungssystem.Detector.Signalverarbeitung.Complex object whose value is the complex sine of this
public Complex sin() {
return new Complex(Math.sin(re) * Math.cosh(im), Math.cos(re) * Math.sinh(im));
}
// return a new com.example.ueberwachungssystem.Signalverarbeitung.Complex object whose value is the complex cosine of this
// return a new com.example.ueberwachungssystem.Detector.Signalverarbeitung.Complex object whose value is the complex cosine of this
public Complex cos() {
return new Complex(Math.cos(re) * Math.cosh(im), -Math.sin(re) * Math.sinh(im));
}
// return a new com.example.ueberwachungssystem.Signalverarbeitung.Complex object whose value is the complex tangent of this
// return a new com.example.ueberwachungssystem.Detector.Signalverarbeitung.Complex object whose value is the complex tangent of this
public Complex tan() {
return sin().divides(cos());
}
@@ -1,12 +1,10 @@
package com.example.ueberwachungssystem.Signalverarbeitung;
package com.example.ueberwachungssystem.Detector.Signalverarbeitung;
// Source: https://introcs.cs.princeton.edu/java/97data/FFT.java.html
import android.util.Log;
/******************************************************************************
* Compilation: javac FFT.java
* Execution: java FFT n
* Dependencies: com.example.ueberwachungssystem.Signalverarbeitung.Complex.java
* Dependencies: com.example.ueberwachungssystem.Detector.Signalverarbeitung.Complex.java
*
* Compute the FFT and inverse FFT of a length n complex sequence
* using the radix 2 Cooley-Tukey algorithm.
@@ -158,7 +156,7 @@ public class FFT {
return y;
}
// display an array of com.example.ueberwachungssystem.Signalverarbeitung.Complex numbers to standard output
// display an array of com.example.ueberwachungssystem.Detector.Signalverarbeitung.Complex numbers to standard output
public static void show(Complex[] x, String title) {
System.out.println(title);
System.out.println("-------------------");
@@ -1,20 +1,21 @@
package com.example.ueberwachungssystem;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Switch;
import android.widget.TextView;
import com.example.ueberwachungssystem.logger.Logger;
import com.example.ueberwachungssystem.Detector.DetectionReport;
import com.example.ueberwachungssystem.Detector.Detector;
import com.example.ueberwachungssystem.Detector.MicrophoneDetector;
import com.jjoe64.graphview.GraphView;
public class MainActivity extends AppCompatActivity {
Logger logger;
GraphView graph;
private TextView tv_log;
MicrophoneDetector Mic;
private Switch TglBtn_Mic;
@@ -23,24 +24,28 @@ public class MainActivity extends AppCompatActivity {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_log = (TextView) findViewById(R.id.tv_log); //Set textview for showing logged content
logger = new Logger(this.getClass().getSimpleName(), tv_log, "");
logger.log(this.getClass().getSimpleName() + ".onCreate");
graph = (GraphView) findViewById(R.id.graph);
Mic = new MicrophoneDetector(this, logger, graph);
Log.d("Main",this.getClass().getSimpleName() + ".onCreate");
Mic = new MicrophoneDetector(this);
setupMic();
Mic.setOnDetectionListener(new Detector.OnDetectionListener() {
@Override
public void onDetection(@NonNull DetectionReport detectionReport) {
Log.d("Main", "Detection erkannt!");
}
});
}
@Override
public void onResume() {
super.onResume();
logger.log(this.getClass().getSimpleName() + ".onResume");
Log.d("Main",this.getClass().getSimpleName() + ".onResume");
}
@Override
public void onPause() {
super.onPause();
logger.log(this.getClass().getSimpleName() + ".onPause");
Log.d("Main",this.getClass().getSimpleName() + ".onPause");
}
private void setupMic() {
@@ -49,12 +54,11 @@ public class MainActivity extends AppCompatActivity {
@Override
public void onClick(View v) {
if (v == TglBtn_Mic) {
logger.log("onClick toggleButtonThread " + TglBtn_Mic.isChecked());
Log.d("Main","onClick toggleButtonThread " + TglBtn_Mic.isChecked());
if (TglBtn_Mic.isChecked()) {
Mic.startDetection();
} else {
Mic.stopDetection();
logger.clearLog();
}
}
}
@@ -1,61 +0,0 @@
package com.example.ueberwachungssystem.logger;
import android.util.Log;
import android.widget.TextView;
import java.io.PrintWriter;
import java.io.StringWriter;
public class Logger {
private TextView textView;
private StringBuffer sb = new StringBuffer();
private String tag;
private int lengthOfLastLog = 0;
private boolean overwrite = false;
public Logger(String tag, TextView textView, String logInitText) {
this.tag = tag;
this.textView = textView;
sb.append(logInitText);
}
public void log(String s) {
overwrite = false;
Log.d(tag, s);
sb.append(s).append("\n");
if (textView != null) {
textView.setText(sb.toString());
}
}
public void overwriteLastlog(String s) {
Log.d(tag, s);
lengthOfLastLog = s.length();
if (overwrite)
{
sb.setLength(sb.length() - (lengthOfLastLog + 1));
}
sb.append(s).append("\n");
overwrite = true;
if (textView != null) {
textView.setText(sb.toString());
}
}
public void log(Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log(sw.toString());
}
public void clearLog() {
sb.setLength(0);
if (textView != null) {
textView.setText("");
}
}
public String getLoggedText() {
return sb.toString();
}
}
+1 -12
View File
@@ -11,6 +11,7 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Log"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/TglBtn_Mic" />
@@ -22,16 +23,4 @@
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.jjoe64.graphview.GraphView
android:id="@+id/graph"
android:layout_width="match_parent"
android:layout_height="200dip"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.499" />
</androidx.constraintlayout.widget.ConstraintLayout>