Haven is for people who need a way to protect their personal spaces and possessions without compromising their own privacy, through an Android app and on-device sensors
Wireless networks project, first commit
Marco Ziccardi13c3e21cd6b8
diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..cc2df6f--- /dev/null+++ b/.gitignore@@ -0,0 +1,26 @@+# gedit temporary+*~++# built application files+*.apk+*.ap_++# files for the dex VM+*.dex++# Java class files+*.class++# generated files+bin/+gen/++# Local configuration file (sdk path, etc)+local.properties++# Eclipse project files+.classpath+.project++# Proguard folder generated by Eclipse+proguard/diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefsnew file mode 100644index 0000000..f77b31c--- /dev/null+++ b/.settings/org.eclipse.jdt.core.prefs@@ -0,0 +1,4 @@+eclipse.preferences.version=1+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5+org.eclipse.jdt.core.compiler.compliance=1.5+org.eclipse.jdt.core.compiler.source=1.5diff --git a/AndroidManifest.xml b/AndroidManifest.xmlnew file mode 100644index 0000000..f9b1dd0--- /dev/null+++ b/AndroidManifest.xml@@ -0,0 +1,40 @@+<manifest xmlns:android="http://schemas.android.com/apk/res/android"+ package="me.ziccard.secureit"+ android:versionCode="1"+ android:versionName="1.0" >++ <uses-permission android:name="android.permission.INTERNET" />+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />+ <uses-permission android:name="android.permission.CAMERA" />+ <uses-permission android:name="android.permission.RECORD_AUDIO"/>+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>+ <uses-permission android:name="android.permission.BLUETOOTH" />+ <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />+ <uses-feature android:name="android.hardware.camera" />+ <uses-feature android:name="android.hardware.camera.autofocus" />+ <uses-feature android:glEsVersion="0x00020000" android:required="true" />++ <uses-sdk+ android:minSdkVersion="11"+ android:targetSdkVersion="15" />++ <application+ android:icon="@drawable/ic_launcher"+ android:label="@string/app_name"+ android:theme="@style/AppTheme" >+ <activity+ android:name=".StartActivity"+ android:label="@string/title_activity_start" >+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LAUNCHER" />+ </intent-filter>+ </activity>+ <activity android:label="@string/app_name" android:name=".MonitorFragment"/>+ <activity+ android:label="@string/app_name"+ android:name=".MonitorActivity"+ android:screenOrientation="portrait"/>+ <service android:name=".service.BluetoothService"/>+ </application>+</manifest>\ No newline at end of filediff --git a/libs/Androidplot-core-0.5.0-release.jar b/libs/Androidplot-core-0.5.0-release.jarnew file mode 100644index 0000000..40606a3Binary files /dev/null and b/libs/Androidplot-core-0.5.0-release.jar differdiff --git a/libs/android-support-v4.jar b/libs/android-support-v4.jarnew file mode 100644index 0000000..feaf44fBinary files /dev/null and b/libs/android-support-v4.jar differdiff --git a/project.properties b/project.propertiesnew file mode 100644index 0000000..a9d0f5a--- /dev/null+++ b/project.properties@@ -0,0 +1,15 @@+# This file is automatically generated by Android Tools.+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!+#+# This file must be checked in Version Control Systems.+#+# To customize properties used by the Ant build system edit+# "ant.properties", and override values to adapt the script to your+# project structure.+#+# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):+#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt++# Project target.+target=android-16+android.library.reference.1=../Android-ViewPagerIndicator/librarydiff --git a/res/drawable-hdpi/ic_action_search.png b/res/drawable-hdpi/ic_action_search.pngnew file mode 100644index 0000000..67de12dBinary files /dev/null and b/res/drawable-hdpi/ic_action_search.png differdiff --git a/res/drawable-hdpi/ic_launcher.png b/res/drawable-hdpi/ic_launcher.pngnew file mode 100644index 0000000..aa1a6ecBinary files /dev/null and b/res/drawable-hdpi/ic_launcher.png differdiff --git a/res/drawable-ldpi/ic_launcher.png b/res/drawable-ldpi/ic_launcher.pngnew file mode 100644index 0000000..fb0a032Binary files /dev/null and b/res/drawable-ldpi/ic_launcher.png differdiff --git a/res/drawable-mdpi/ic_action_search.png b/res/drawable-mdpi/ic_action_search.pngnew file mode 100644index 0000000..134d549Binary files /dev/null and b/res/drawable-mdpi/ic_action_search.png differdiff --git a/res/drawable-mdpi/ic_launcher.png b/res/drawable-mdpi/ic_launcher.pngnew file mode 100644index 0000000..3eeaf61Binary files /dev/null and b/res/drawable-mdpi/ic_launcher.png differdiff --git a/res/drawable-xhdpi/ic_action_search.png b/res/drawable-xhdpi/ic_action_search.pngnew file mode 100644index 0000000..d699c6bBinary files /dev/null and b/res/drawable-xhdpi/ic_action_search.png differdiff --git a/res/drawable-xhdpi/ic_launcher.png b/res/drawable-xhdpi/ic_launcher.pngnew file mode 100644index 0000000..e037b4fBinary files /dev/null and b/res/drawable-xhdpi/ic_launcher.png differdiff --git a/res/drawable/back.xml b/res/drawable/back.xmlnew file mode 100644index 0000000..0a78175--- /dev/null+++ b/res/drawable/back.xml@@ -0,0 +1,7 @@+<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >+ <solid android:color="#ffffff" />+ <stroke android:width="2dip" android:color="#000000"/>+ <padding android:left="7dp" android:top="7dp"+ android:right="7dp" android:bottom="7dp" />+ <corners android:radius="4dp" />+</shape>\ No newline at end of filediff --git a/res/drawable/backtx.bmp b/res/drawable/backtx.bmpnew file mode 100644index 0000000..ab16eadBinary files /dev/null and b/res/drawable/backtx.bmp differdiff --git a/res/drawable/black_white_gradient.xml b/res/drawable/black_white_gradient.xmlnew file mode 100644index 0000000..579b804--- /dev/null+++ b/res/drawable/black_white_gradient.xml@@ -0,0 +1,8 @@+<shape xmlns:android="http://schemas.android.com/apk/res/android"+ android:shape="rectangle">+ <gradient+ android:startColor="#00000000"+ android:centerColor="#FFFFFFFF"+ android:endColor="#00000000"+ android:angle="0" />+</shape>\ No newline at end of filediff --git a/res/drawable/fronttx.bmp b/res/drawable/fronttx.bmpnew file mode 100644index 0000000..e16276aBinary files /dev/null and b/res/drawable/fronttx.bmp differdiff --git a/res/drawable/red_back.xml b/res/drawable/red_back.xmlnew file mode 100644index 0000000..d322c39--- /dev/null+++ b/res/drawable/red_back.xml@@ -0,0 +1,7 @@+<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >+ <solid android:color="#ffffff" />+ <stroke android:width="2dip" android:color="#FF0000"/>+ <padding android:left="7dp" android:top="7dp"+ android:right="7dp" android:bottom="7dp" />+ <corners android:radius="4dp" />+</shape>\ No newline at end of filediff --git a/res/layout/accelerometer_fragment.xml b/res/layout/accelerometer_fragment.xmlnew file mode 100644index 0000000..f25e4ee--- /dev/null+++ b/res/layout/accelerometer_fragment.xml@@ -0,0 +1,37 @@+<?xml version="1.0" encoding="utf-8"?>++<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"+ android:layout_width="fill_parent"+ android:orientation="vertical"+ android:layout_height="wrap_content">++ <TextView+ android:id="@+id/accelerometer_text"+ android:layout_centerHorizontal="true"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ />++ <TextView+ android:id="@+id/magnetic_field_text"+ android:layout_below="@id/accelerometer_text"+ android:layout_centerHorizontal="true"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ />++ <TextView+ android:id="@+id/orientation_text"+ android:layout_below="@id/magnetic_field_text"+ android:layout_centerHorizontal="true"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ />++ <FrameLayout android:id="@+id/opengl"+ android:layout_below="@id/orientation_text"+ android:layout_centerHorizontal="true"+ android:layout_width="fill_parent"+ android:layout_height="fill_parent">+ </FrameLayout>+</RelativeLayout>\ No newline at end of filediff --git a/res/layout/activity_monitor.xml b/res/layout/activity_monitor.xmlnew file mode 100644index 0000000..fa79d4d--- /dev/null+++ b/res/layout/activity_monitor.xml@@ -0,0 +1,21 @@+<?xml version="1.0" encoding="utf-8"?>+<LinearLayout+ xmlns:android="http://schemas.android.com/apk/res/android"+ android:orientation="vertical"+ android:layout_width="fill_parent"+ android:layout_height="fill_parent">++ <com.viewpagerindicator.TitlePageIndicator+ android:id="@+id/indicator"+ android:padding="10dip"+ android:layout_height="wrap_content"+ android:layout_width="fill_parent"+ />+ <android.support.v4.view.ViewPager+ android:id="@+id/pager"+ android:layout_width="fill_parent"+ android:layout_height="0dp"+ android:layout_weight="1"+ />++</LinearLayout>\ No newline at end of filediff --git a/res/layout/activity_start.xml b/res/layout/activity_start.xmlnew file mode 100644index 0000000..6bf1a7d--- /dev/null+++ b/res/layout/activity_start.xml@@ -0,0 +1,239 @@+<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"+ xmlns:tools="http://schemas.android.com/tools"+ android:layout_width="fill_parent"+ android:layout_height="fill_parent">++<RelativeLayout+ android:layout_width="match_parent"+ android:layout_height="match_parent" >++ <CheckBox+ android:id="@+id/accelerometer_check"+ android:text="@string/accelerometer_label"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_centerHorizontal="true"+ tools:context=".StartActivity" />++ <RelativeLayout+ android:background="@drawable/back"+ android:layout_below="@id/accelerometer_check"+ android:id="@+id/accelerometer_options"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:visibility="gone"+ android:paddingLeft="30dp"+ android:paddingRight="30dp"+ android:layout_marginLeft="20dp"+ android:layout_marginRight="20dp">+ <TextView+ android:id="@+id/accelerometer_prompt"+ android:text="@string/accelerometer_prompt"+ android:layout_alignParentLeft="true"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:paddingTop="10dp"+ />+ <Spinner+ android:id="@+id/accelerometer_sensitivity_spinner"+ android:layout_alignParentRight="true"+ android:prompt="@string/accelerometer_prompt"+ android:entries="@array/accelerometer_sensitivity"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_centerHorizontal="true"+ />++ </RelativeLayout>++ <CheckBox+ android:id="@+id/camera_check"+ android:text="@string/camera_label"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_centerHorizontal="true"+ tools:context=".StartActivity"+ android:layout_below="@id/accelerometer_options"/>+ <RelativeLayout+ android:background="@drawable/back"+ android:layout_below="@id/camera_check"+ android:id="@+id/camera_options"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:visibility="gone"+ android:paddingLeft="30dp"+ android:paddingRight="30dp"+ android:layout_marginLeft="20dp"+ android:layout_marginRight="20dp">+ <CheckBox+ android:id="@+id/flash_check"+ android:text="@string/flash_label"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_centerHorizontal="true"+ tools:context=".StartActivity"+ />+ <TextView+ android:id="@+id/camera_prompt"+ android:text="@string/camera_prompt"+ android:layout_alignParentLeft="true"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:paddingTop="10dp"+ android:layout_below="@id/flash_check"+ />+ <Spinner+ android:id="@+id/camera_spinner"+ android:layout_alignParentRight="true"+ android:prompt="@string/camera_prompt"+ android:entries="@array/select_camera"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_centerHorizontal="true"+ android:layout_below="@id/flash_check"+ />+ <TextView+ android:id="@+id/camera_sensitivity_prompt"+ android:text="@string/accelerometer_prompt"+ android:layout_alignParentLeft="true"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:paddingTop="10dp"+ android:layout_below="@id/camera_prompt"+ />+ <Spinner+ android:id="@+id/camera_sensitivity_spinner"+ android:layout_alignParentRight="true"+ android:layout_below="@id/camera_spinner"+ android:prompt="@string/accelerometer_prompt"+ android:entries="@array/accelerometer_sensitivity"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_centerHorizontal="true"+ />++ </RelativeLayout>+ <CheckBox+ android:id="@+id/microphone_check"+ android:text="@string/microphone_label"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_centerHorizontal="true"+ tools:context=".StartActivity"+ android:layout_below="@id/camera_options" />++ <RelativeLayout+ android:background="@drawable/back"+ android:layout_below="@id/microphone_check"+ android:id="@+id/microphone_options"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:visibility="gone"+ android:paddingLeft="30dp"+ android:paddingRight="30dp"+ android:layout_marginLeft="20dp"+ android:layout_marginRight="20dp">+ <TextView+ android:id="@+id/microphone_prompt"+ android:text="@string/accelerometer_prompt"+ android:layout_alignParentLeft="true"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:paddingTop="10dp"+ />+ <Spinner+ android:id="@+id/microphone_sensitivity_spinner"+ android:layout_alignParentRight="true"+ android:prompt="@string/accelerometer_prompt"+ android:entries="@array/accelerometer_sensitivity"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_centerHorizontal="true"+ />++ </RelativeLayout>++ <CheckBox+ android:id="@+id/sms_check"+ android:text="@string/sms_label"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_centerHorizontal="true"+ tools:context=".StartActivity"+ android:layout_below="@id/microphone_options" />++ <RelativeLayout+ android:background="@drawable/back"+ android:layout_below="@id/sms_check"+ android:id="@+id/sms_options"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:visibility="gone"+ android:paddingLeft="30dp"+ android:paddingRight="30dp"+ android:layout_marginLeft="20dp"+ android:layout_marginRight="20dp">+ <EditText+ android:id="@+id/phone_number"+ android:hint="@string/sms_hint"+ android:inputType="phone"+ android:layout_centerHorizontal="true"+ android:layout_width="fill_parent"+ android:layout_height="wrap_content"+ android:paddingTop="10dp"+ />++ </RelativeLayout>++ <CheckBox+ android:id="@+id/remote_check"+ android:text="@string/remote_label"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_centerHorizontal="true"+ tools:context=".StartActivity"+ android:layout_below="@id/sms_options" />++ <RelativeLayout+ android:background="@drawable/back"+ android:layout_below="@id/remote_check"+ android:id="@+id/remote_options"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:visibility="gone"+ android:paddingLeft="30dp"+ android:paddingRight="30dp"+ android:layout_marginLeft="20dp"+ android:layout_marginRight="20dp">+ <EditText+ android:id="@+id/email"+ android:hint="@string/email_hint"+ android:inputType="textEmailAddress"+ android:layout_centerHorizontal="true"+ android:layout_width="fill_parent"+ android:layout_height="wrap_content"+ android:paddingTop="10dp"+ />+ <EditText+ android:id="@+id/password"+ android:layout_below="@id/email"+ android:hint="@string/password_hint"+ android:inputType="text"+ android:layout_centerHorizontal="true"+ android:layout_width="fill_parent"+ android:layout_height="wrap_content"+ android:paddingTop="10dp"+ />++ </RelativeLayout>++ <Button+ android:id="@+id/start_button"+ android:text="Start"+ android:layout_below="@id/remote_options"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_centerHorizontal="true"/>++</RelativeLayout>+</ScrollView>\ No newline at end of filediff --git a/res/layout/camera_fragment.xml b/res/layout/camera_fragment.xmlnew file mode 100644index 0000000..92bdbf6--- /dev/null+++ b/res/layout/camera_fragment.xml@@ -0,0 +1,43 @@+<?xml version="1.0" encoding="utf-8"?>++<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"+ android:layout_width="fill_parent"+ android:orientation="vertical"+ android:layout_height="wrap_content">++ <FrameLayout android:id="@+id/preview"+ android:layout_centerHorizontal="true"+ android:layout_width="150dp"+ android:layout_height="200dp">+ </FrameLayout>+++ <ImageView+ android:src="@drawable/ic_launcher"+ android:id="@+id/old_image"+ android:layout_alignParentLeft="true"+ android:layout_width="150dp"+ android:layout_height="200dp"+ android:paddingLeft="20dp"+ android:layout_below="@id/preview"+ />++ <ImageView+ android:id="@+id/new_image"+ android:src="@drawable/ic_launcher"+ android:layout_alignParentRight="true"+ android:layout_width="150dp"+ android:layout_height="200dp"+ android:layout_alignRight="@id/old_image"+ android:paddingRight="20dp"+ android:layout_below="@id/preview"+ />++ <TextView+ android:id="@+id/textview"+ android:layout_centerHorizontal="true"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_below="@id/new_image"+ />+</RelativeLayout>diff --git a/res/layout/empty_fragment.xml b/res/layout/empty_fragment.xmlnew file mode 100644index 0000000..741b33f--- /dev/null+++ b/res/layout/empty_fragment.xml@@ -0,0 +1,28 @@+<?xml version="1.0" encoding="utf-8"?>++<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"+ android:layout_width="fill_parent"+ android:orientation="vertical"+ android:layout_height="wrap_content">++ <RelativeLayout+ android:background="@drawable/red_back"+ android:id="@+id/camera_options"+ android:layout_centerHorizontal="true"+ android:layout_centerVertical="true"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:paddingLeft="30dp"+ android:paddingRight="30dp"+ android:layout_marginLeft="20dp"+ android:layout_marginRight="20dp">++ <TextView+ android:id="@+id/label"+ android:layout_centerHorizontal="true"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ />+ </RelativeLayout>++</RelativeLayout>diff --git a/res/layout/microphone_fragment.xml b/res/layout/microphone_fragment.xmlnew file mode 100644index 0000000..339a114--- /dev/null+++ b/res/layout/microphone_fragment.xml@@ -0,0 +1,23 @@+<?xml version="1.0" encoding="utf-8"?>++<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"+ android:layout_width="fill_parent"+ android:orientation="vertical"+ android:id="@+id/linear_layout"+ android:layout_height="wrap_content">++<!-- <com.androidplot.xy.XYPlot+ android:id="@+id/mySimpleXYPlot"+ android:layout_width="fill_parent"+ android:layout_height="200dp"+ android:layout_marginTop="10dp"+ android:layout_marginLeft="0px"+ android:layout_marginRight="0px"+ title=""+ /> -->++ <TextView xmlns:android="http://schemas.android.com/apk/res/android"+ android:id="@+id/microphone"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"/>+</LinearLayout>\ No newline at end of filediff --git a/res/menu/monitor_activity.xml b/res/menu/monitor_activity.xmlnew file mode 100644index 0000000..4e3c4f3--- /dev/null+++ b/res/menu/monitor_activity.xml@@ -0,0 +1,6 @@+<menu xmlns:android="http://schemas.android.com/apk/res/android">+ <item android:id="@+id/menu_settings"+ android:title="@string/menu_stop"+ android:orderInCategory="100"+ android:showAsAction="never" />+</menu>diff --git a/res/raw/per_pixel_fragment_shader.glsl b/res/raw/per_pixel_fragment_shader.glslnew file mode 100644index 0000000..c459332--- /dev/null+++ b/res/raw/per_pixel_fragment_shader.glsl@@ -0,0 +1,33 @@+precision mediump float; // Set the default precision to medium. We don't need as high of a+ // precision in the fragment shader.+uniform vec3 u_LightPos; // The position of the light in eye space.+uniform sampler2D u_Texture; // The input texture.++varying vec3 v_Position; // Interpolated position for this fragment.+varying vec4 v_Color; // This is the color from the vertex shader interpolated across the+ // triangle per fragment.+varying vec3 v_Normal; // Interpolated normal for this fragment.+varying vec2 v_TexCoordinate; // Interpolated texture coordinate per fragment.++// The entry point for our fragment shader.+void main()+{+ // Will be used for attenuation.+ float distance = length(u_LightPos - v_Position);++ // Get a lighting direction vector from the light to the vertex.+ vec3 lightVector = normalize(u_LightPos - v_Position);++ // Calculate the dot product of the light vector and vertex normal. If the normal and light vector are+ // pointing in the same direction then it will get max illumination.+ float diffuse = max(dot(v_Normal, lightVector), 0.0);++ // Add attenuation.+ diffuse = diffuse * (1.0 / (1.0 + (0.10 * distance)));++ // Add ambient lighting+ diffuse = diffuse + 0.3;++ // Multiply the color by the diffuse illumination level and texture value to get final output color.+ gl_FragColor = (v_Color * diffuse * texture2D(u_Texture, v_TexCoordinate));+}diff --git a/res/raw/per_pixel_vertex_shader.glsl b/res/raw/per_pixel_vertex_shader.glslnew file mode 100644index 0000000..1d02117--- /dev/null+++ b/res/raw/per_pixel_vertex_shader.glsl@@ -0,0 +1,32 @@+uniform mat4 u_MVPMatrix; // A constant representing the combined model/view/projection matrix.+uniform mat4 u_MVMatrix; // A constant representing the combined model/view matrix.++attribute vec4 a_Position; // Per-vertex position information we will pass in.+attribute vec4 a_Color; // Per-vertex color information we will pass in.+attribute vec3 a_Normal; // Per-vertex normal information we will pass in.+attribute vec2 a_TexCoordinate; // Per-vertex texture coordinate information we will pass in.++varying vec3 v_Position; // This will be passed into the fragment shader.+varying vec4 v_Color; // This will be passed into the fragment shader.+varying vec3 v_Normal; // This will be passed into the fragment shader.+varying vec2 v_TexCoordinate; // This will be passed into the fragment shader.++// The entry point for our vertex shader.+void main()+{+ // Transform the vertex into eye space.+ v_Position = vec3(u_MVMatrix * a_Position);++ // Pass through the color.+ v_Color = a_Color;++ // Pass through the texture coordinate.+ v_TexCoordinate = a_TexCoordinate;++ // Transform the normal's orientation into eye space.+ v_Normal = vec3(u_MVMatrix * vec4(a_Normal, 0.0));++ // gl_Position is a special variable used to store the final position.+ // Multiply the vertex by the matrix to get the final point in normalized screen coordinates.+ gl_Position = u_MVPMatrix * a_Position;+}\ No newline at end of filediff --git a/res/values-v11/styles.xml b/res/values-v11/styles.xmlnew file mode 100644index 0000000..d408cbc--- /dev/null+++ b/res/values-v11/styles.xml@@ -0,0 +1,5 @@+<resources>++ <style name="AppTheme" parent="android:Theme.Holo.Light" />++</resources>\ No newline at end of filediff --git a/res/values-v14/styles.xml b/res/values-v14/styles.xmlnew file mode 100644index 0000000..1c089a7--- /dev/null+++ b/res/values-v14/styles.xml@@ -0,0 +1,5 @@+<resources>++ <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar" />++</resources>\ No newline at end of filediff --git a/res/values/strings.xml b/res/values/strings.xmlnew file mode 100644index 0000000..ac632ab--- /dev/null+++ b/res/values/strings.xml@@ -0,0 +1,69 @@+<resources>++ <string name="app_name">SecureIt</string>+ <string name="hello_world">Hello world!</string>+ <string name="menu_stop">Stop</string>+ <string name="title_activity_start">StartActivity</string>++ <string name="accelerometer_label">+ Use accelerometer to detect motion+ </string>+ <string name="accelerometer_prompt">+ Set sensitivity+ </string>++ <string name="microphone_label">+ Use microphone to detect any sound+ </string>++ <string name="camera_label">+ Use the camera to detect motion+ </string>++ <string name="flash_label">+ Activate the flash+ </string>++ <string name="sms_label">+ Send an SMS as alert+ </string>++ <string name="remote_label">+ Send alert data to SecureIt+ </string>++ <string name="sms_hint">+ Phone+ </string>++ <string name="email_hint">+ </string>++ <string name="password_hint">+ Password+ </string>++ <string name="camera_prompt">+ Select the camera+ </string>++ <array name="accelerometer_sensitivity">+ <item>Low</item>+ <item>Medium</item>+ <item>High</item>+ </array>+ <array name="select_camera">+ <item>Front</item>+ <item>Back</item>+ </array>++ <string name="secure_service_started">+ Home security deamon started+ </string>++ <string name="secure_service_stopped">+ Home security deamon stopped+ </string>++</resources>\ No newline at end of filediff --git a/res/values/styles.xml b/res/values/styles.xmlnew file mode 100644index 0000000..4dba0d0--- /dev/null+++ b/res/values/styles.xml@@ -0,0 +1,5 @@+<resources>++ <style name="AppTheme" parent="android:Theme.Light" />++</resources>\ No newline at end of filediff --git a/src/me/ziccard/secureit/MicrophoneVolumePicker.java b/src/me/ziccard/secureit/MicrophoneVolumePicker.javanew file mode 100644index 0000000..9aad698--- /dev/null+++ b/src/me/ziccard/secureit/MicrophoneVolumePicker.java@@ -0,0 +1,80 @@+package me.ziccard.secureit;++import android.content.Context;+import android.graphics.Canvas;+import android.graphics.Color;+import android.graphics.Paint;+import android.graphics.Rect;+import android.util.Log;+import android.view.Display;+import android.view.View;++public class MicrophoneVolumePicker extends View {+ Paint paint = new Paint();++ final int GREEN = 8453888;+ final int ORANGE = 16744448;+ final int RED = 14549506;++ public MicrophoneVolumePicker(Context context) {+ super(context);+ }++ @Override+ public void onDraw(Canvas canvas) {+ int paddingBorder = 30; // padding from border+ int scaleSize = canvas.getWidth()-paddingBorder*2; // due bordi destro e sinistro.++ int zeroDBPoint = scaleSize/3*2; // 0db is placed 2/3 of the available screen+ int ambientNoisePoint = scaleSize/3;++ final int bottomScale = -50;+ final int ambientDBValue = -10; // in db;+ int currentValue = 2; //value recorded by mic+ double currentValueWithinScale = currentValue - bottomScale; // bottomscale = 0+ if(currentValue < ambientDBValue){+ final double underAmbientGrain = Math.abs(bottomScale-ambientDBValue);++ paint.setColor(GREEN);+ //(currentValueWithinScale)*ambientNoisePoint+ canvas.drawRect(new Rect(paddingBorder,+ paddingBorder,+ (int) (paddingBorder+(currentValueWithinScale/underAmbientGrain)*ambientNoisePoint),+ paddingBorder+30),+ paint);+ Log.i("DEBUG:",""+(currentValueWithinScale/underAmbientGrain)+":"+ambientNoisePoint);+ } else {+ // paint the undernoise part+ paint.setColor(Color.GREEN);+ canvas.drawRect(new Rect(paddingBorder,+ paddingBorder,+ paddingBorder+ambientNoisePoint,+ paddingBorder+30), paint);++ if(currentValue < 0){+ // paint the noise to 0 db part++ } else {+ paint.setColor(Color.YELLOW);+ canvas.drawRect(paddingBorder+ambientNoisePoint,+ paddingBorder,+ paddingBorder+zeroDBPoint,+ paddingBorder+30,+ paint );++++ }+ }+++ /*+ paint.setColor(Color.YELLOW);+ canvas.drawRect(33, 60, 77, 77, paint );+ paint.setColor(Color.RED);+ canvas.drawRect(33, 33, 77, 60, paint );+ */++ }++}\ No newline at end of filediff --git a/src/me/ziccard/secureit/MonitorActivity.java b/src/me/ziccard/secureit/MonitorActivity.javanew file mode 100644index 0000000..be08f25--- /dev/null+++ b/src/me/ziccard/secureit/MonitorActivity.java@@ -0,0 +1,121 @@+package me.ziccard.secureit;++import me.ziccard.secureit.fragment.AccelerometerFragment;+import me.ziccard.secureit.fragment.CameraFragment;+import me.ziccard.secureit.fragment.EmptyFragment;+import me.ziccard.secureit.fragment.MicrophoneFragment;+import me.ziccard.secureit.service.BluetoothService;+import android.content.Context;+import android.content.Intent;+import android.os.Bundle;+import android.support.v4.app.Fragment;+import android.support.v4.app.FragmentActivity;+import android.support.v4.app.FragmentManager;+import android.support.v4.app.FragmentPagerAdapter;+import android.support.v4.view.ViewPager;+import android.view.Menu;+import android.view.MenuItem;++import com.viewpagerindicator.TitlePageIndicator;+import com.viewpagerindicator.TitlePageIndicator.IndicatorStyle;++public class MonitorActivity extends FragmentActivity {++ private SecureItPreferences preferences = null;++ private static final String[] CONTENT = new String[] { "Accel.", "Camera",+ "Mic."};+ @Override+ protected void onCreate(Bundle savedInstanceState) {+ super.onCreate(savedInstanceState);++ preferences = new SecureItPreferences(getApplicationContext());++ setContentView(R.layout.activity_monitor);++ FragmentPagerAdapter adapter = new MonitorAdapter(+ getSupportFragmentManager());++ ViewPager pager = (ViewPager)findViewById(R.id.pager);+ pager.setAdapter(adapter);++ TitlePageIndicator indicator = (TitlePageIndicator)findViewById(R.id.indicator);+ indicator.setViewPager(pager);+ final float density = getResources().getDisplayMetrics().density;+ indicator.setBackgroundColor(0x18FF0000);+ indicator.setFooterColor(0xFFAA2222);+ indicator.setFooterLineHeight(1 * density); //1dp+ indicator.setFooterIndicatorHeight(3 * density); //3dp+ indicator.setFooterIndicatorStyle(IndicatorStyle.Underline);+ indicator.setTextColor(0xAA000000);+ indicator.setSelectedColor(0xFF000000);+ indicator.setSelectedBold(true);++ pager.setCurrentItem(1);++ /**+ * Binding to the bluetooth service+ */+ startService(new Intent(this, BluetoothService.class));+ }++ class MonitorAdapter extends FragmentPagerAdapter {+ public MonitorAdapter(FragmentManager fm) {+ super(fm);+ }++ @Override+ public Fragment getItem(int position) {+ switch(position) {+ case 0:+ if (preferences.getAccelerometerActivation())+ return new AccelerometerFragment();+ else+ return EmptyFragment.newInstance(CONTENT[0]);++ case 1:+ if (preferences.getCameraActivation())+ return new CameraFragment();+ else+ return EmptyFragment.newInstance(CONTENT[1]);+ case 2:+ if (preferences.getMicrophoneActivation())+ return new MicrophoneFragment();+ else+ return EmptyFragment.newInstance(CONTENT[2]);+ }+ return null;+ }++ @Override+ public CharSequence getPageTitle(int position) {+ return CONTENT[position % CONTENT.length].toUpperCase();+ }+++ @Override+ public int getCount() {+ return CONTENT.length;+ }+ }++ @Override+ public boolean onCreateOptionsMenu(Menu menu) {+ getMenuInflater().inflate(R.menu.monitor_activity, menu);+ return true;+ }++ @Override+ public boolean onOptionsItemSelected (MenuItem item) {+ switch (item.getItemId()){+ case R.id.menu_settings:+ Intent intent = new Intent(+ getApplicationContext(), StartActivity.class);+ intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);+ startActivity(intent);+ stopService(new Intent(this, BluetoothService.class));+ break;+ }+ return true;+ }+}diff --git a/src/me/ziccard/secureit/Preview.java b/src/me/ziccard/secureit/Preview.javanew file mode 100644index 0000000..0fe50c1--- /dev/null+++ b/src/me/ziccard/secureit/Preview.java@@ -0,0 +1,222 @@+package me.ziccard.secureit;++import java.io.File;+import java.io.FileNotFoundException;+import java.io.FileOutputStream;+import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import me.ziccard.secureit.async.MotionAsyncTask;+import me.ziccard.secureit.async.MotionAsyncTask.MotionListener;+import me.ziccard.secureit.codec.ImageCodec;+import android.content.Context;+import android.graphics.Bitmap;+import android.graphics.Rect;+import android.graphics.YuvImage;+import android.hardware.Camera;+import android.hardware.Camera.PreviewCallback;+import android.hardware.Camera.Size;+import android.os.Environment;+import android.os.Handler;+import android.util.Log;+import android.view.SurfaceHolder;+import android.view.SurfaceView;+import android.view.Surface;+import android.view.WindowManager;+import android.view.Display;+import android.widget.Toast;++public class Preview extends SurfaceView implements SurfaceHolder.Callback {++ private List<MotionListener> listeners = new ArrayList<MotionListener>();++ /**+ * Timestamp of the last picture processed+ */+ private long lastTimestamp;+ /**+ * Last picture processed+ */+ private int[] lastPic;+ /**+ * True IFF there's an async task processing images+ */+ private boolean doingProcessing;++ /**+ * Handler used to update back the UI after motion detection+ */+ private final Handler updateHandler = new Handler();++ /**+ * Last frame captured+ */+ private int imageCount = 0;++ /**+ * Max number of pictures stored+ */+ private static final int MAX_IMAGES = 10;++ /**+ * PATH to the directory where to save images+ */+ private static final String FILE = "/secureit";+++ SurfaceHolder mHolder;+ public Camera camera;+ private Context context;++ public Preview (Context context) {+ super(context);+ this.context = context;+ // Install a SurfaceHolder.Callback so we get notified when the+ // underlying surface is created and destroyed.+ mHolder = getHolder();+ mHolder.addCallback(this);+ }++ public void addListener(MotionListener listener) {+ listeners.add(listener);+ }+++ /**+ * Called on the creation of the surface:+ * setting camera parameters to lower possible resolution+ * (preferred is 640x480)+ * in order to minimize CPU usage+ */+ public void surfaceCreated(SurfaceHolder holder) {+ // The Surface has been created, acquire the camera and tell it where+ // to draw.+ camera = Camera.open();+ final Camera.Parameters parameters = camera.getParameters();+ List<Size> sizes = parameters.getSupportedPictureSizes();+ int w = 640;+ int h = 480;+ for (Size s : sizes) {+ Log.i("SurfaceView", "width: "+s.width+" height: "+s.height);+ if (s.width <= 640) {+ w = s.width;+ h = s.height;+ Log.i("SurfaceView", "selected width: "+w+" selected height: "+h);+ break;+ }+ }+ parameters.setPictureSize(w, h);+ try {+ camera.setPreviewDisplay(mHolder);++ camera.setPreviewCallback(new PreviewCallback() {++ public void onPreviewFrame(byte[] data, Camera cam) {++ final Camera.Size size = cam.getParameters().getPreviewSize();+ if (size == null) return;+ long now = System.currentTimeMillis();+ if (now < Preview.this.lastTimestamp + 1000)+ return;+ if (!doingProcessing) {++ /**+ * Before processing the frame we save it+ * to the SDCARD+ */+ try {+ YuvImage image = new YuvImage(data, parameters.getPreviewFormat(),+ size.width, size.height, null);++ imageCount = (imageCount + 1)%11;++ File file = new File(Environment.getExternalStorageDirectory()+ .getPath() + FILE + imageCount + ".jpg");++ FileOutputStream filecon = new FileOutputStream(file);+ image.compressToJpeg(+ new Rect(0, 0, image.getWidth(), image.getHeight()), 90,+ filecon);+ } catch (FileNotFoundException e) {+ Toast toast = Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG);+ toast.show();+ }++ Log.i("Preview", "Processing new image");+ Preview.this.lastTimestamp = now;+ MotionAsyncTask task = new MotionAsyncTask(+ lastPic,+ data,+ size.width,+ size.height,+ updateHandler);+ for (MotionListener listener : listeners) {+ Log.i("Preview", "Added listener");+ task.addListener(listener);+ }+ doingProcessing = true;+ task.addListener(new MotionListener() {++ public void onProcess(Bitmap oldBitmap, Bitmap newBitmap,+ boolean motionDetected) {+ Log.i("MotionListener", "Allowing further processing");+ doingProcessing = false;+ }+ });+ task.start();+ lastPic = ImageCodec.N21toLuma(+ data,+ size.width,+ size.height);+ }+ }+ });+ } catch (IOException e) {+ e.printStackTrace();+ }+ }++ public void surfaceDestroyed(SurfaceHolder holder) {+ // Surface will be destroyed when we return, so stop the preview.+ // Because the CameraDevice object is not a shared resource, it's very+ // important to release it when the activity is paused.++ camera.stopPreview();+ camera.release();+ camera = null;+ }++ public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {+ // Now that the size is known, set up the camera parameters and begin+ // the preview.+ Camera.Parameters parameters = camera.getParameters();+ parameters.setPreviewSize(w, h);++ Display display = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();++ if(display.getRotation() == Surface.ROTATION_0)+ {+ parameters.setPreviewSize(h, w);+ camera.setDisplayOrientation(90);+ }++ if(display.getRotation() == Surface.ROTATION_90)+ {+ parameters.setPreviewSize(w, h);+ }++ if(display.getRotation() == Surface.ROTATION_180)+ {+ parameters.setPreviewSize(h, w);+ }++ if(display.getRotation() == Surface.ROTATION_270)+ {+ parameters.setPreviewSize(w, h);+ camera.setDisplayOrientation(180);+ }+ camera.setParameters(parameters);+ camera.startPreview();+ }+}\ No newline at end of filediff --git a/src/me/ziccard/secureit/SecureItPreferences.java b/src/me/ziccard/secureit/SecureItPreferences.javanew file mode 100644index 0000000..80c6707--- /dev/null+++ b/src/me/ziccard/secureit/SecureItPreferences.java@@ -0,0 +1,148 @@+package me.ziccard.secureit;++import android.app.Activity;+import android.content.Context;+import android.content.SharedPreferences;+import android.content.SharedPreferences.Editor;++public class SecureItPreferences {++ private SharedPreferences appSharedPrefs;+ private Editor prefsEditor;++ public static final String LOW = "Low";+ public static final String MEDIUM = "Medium";+ public static final String HIGH = "High";++ public static final String FRONT = "Front";+ public static final String BACK = "Back";++ private static final String APP_SHARED_PREFS="me.ziccard.secureit";+ private static final String ACCELEROMETER_ACTIVE="accelerometer_active";+ private static final String ACCELEROMETER_SENSITIVITY="accelerometer_sensibility";+ private static final String CAMERA_ACTIVE="camera_active";+ private static final String CAMERA="camera";+ private static final String CAMERA_SENSITIVITY="camera_sensitivity";+ private static final String FLASH_ACTIVE="flash_active";+ private static final String MICROPHONE_ACTIVE="microphone_active";+ private static final String MICROPHONE_SENSITIVITY="microphone_sensitivity";+ private static final String SMS_ACTIVE="sms_active";+ private static final String SMS_NUMBER="sms_number";+ private static final String REMOTE_ACTIVE="remote_active";+ private static final String REMOTE_EMAIL="remote_email";+++ public SecureItPreferences(Context context) {+ this.appSharedPrefs = context.getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE);+ this.prefsEditor = appSharedPrefs.edit();+ }++ public void activateAccelerometer(boolean active) {+ prefsEditor.putBoolean(ACCELEROMETER_ACTIVE, active);+ prefsEditor.commit();+ }++ public boolean getAccelerometerActivation() {+ return appSharedPrefs.getBoolean(ACCELEROMETER_ACTIVE, true);+ }++ public void setAccelerometerSensitivity(String sensitivity) {+ prefsEditor.putString(ACCELEROMETER_SENSITIVITY, sensitivity);+ prefsEditor.commit();+ }++ public String getAccelerometerSensitivity() {+ return appSharedPrefs.getString(ACCELEROMETER_SENSITIVITY, "");+ }++ public void activateCamera(boolean active) {+ prefsEditor.putBoolean(CAMERA_ACTIVE, active);+ prefsEditor.commit();+ }++ public boolean getCameraActivation() {+ return appSharedPrefs.getBoolean(CAMERA_ACTIVE, true);+ }++ public void setCamera(String camera) {+ prefsEditor.putString(CAMERA, camera);+ prefsEditor.commit();+ }++ public String getCamera() {+ return appSharedPrefs.getString(CAMERA, BACK);+ }++ public void setCameraSensitivity(String sensitivity) {+ prefsEditor.putString(CAMERA_SENSITIVITY, sensitivity);+ prefsEditor.commit();+ }++ public String getCameraSensitivity() {+ return appSharedPrefs.getString(CAMERA_SENSITIVITY, "");+ }++ public void activateFlash(boolean active) {+ prefsEditor.putBoolean(FLASH_ACTIVE, active);+ prefsEditor.commit();+ }++ public boolean getFlashActivation() {+ return appSharedPrefs.getBoolean(FLASH_ACTIVE, true);+ }++ public void activateMicrophone(boolean active) {+ prefsEditor.putBoolean(MICROPHONE_ACTIVE, active);+ prefsEditor.commit();+ }++ public boolean getMicrophoneActivation() {+ return appSharedPrefs.getBoolean(MICROPHONE_ACTIVE, true);+ }++ public void setMicrophoneSensitivity(String sensitivity) {+ prefsEditor.putString(MICROPHONE_SENSITIVITY, sensitivity);+ prefsEditor.commit();+ }++ public String getMicrophoneSensitivity() {+ return appSharedPrefs.getString(MICROPHONE_SENSITIVITY, "");+ }++ public void activateSms(boolean active) {+ prefsEditor.putBoolean(SMS_ACTIVE, active);+ prefsEditor.commit();+ }++ public boolean getSmsActivation() {+ return appSharedPrefs.getBoolean(SMS_ACTIVE, true);+ }++ public void setSmsNumber(String number) {+ prefsEditor.putString(SMS_NUMBER, number);+ prefsEditor.commit();+ }++ public String getSmsNumber() {+ return appSharedPrefs.getString(SMS_NUMBER, "");+ }++ public void activateRemote(boolean active) {+ prefsEditor.putBoolean(REMOTE_ACTIVE, active);+ prefsEditor.commit();+ }++ public boolean getRemoteActivation() {+ return appSharedPrefs.getBoolean(REMOTE_ACTIVE, true);+ }++ public void setRemoteEmail(String email) {+ prefsEditor.putString(REMOTE_EMAIL, email);+ prefsEditor.commit();+ }++ public String getRemoteEmail() {+ return appSharedPrefs.getString(REMOTE_EMAIL, "");+ }++}diff --git a/src/me/ziccard/secureit/StartActivity.java b/src/me/ziccard/secureit/StartActivity.javanew file mode 100644index 0000000..9c36ebf--- /dev/null+++ b/src/me/ziccard/secureit/StartActivity.java@@ -0,0 +1,261 @@+package me.ziccard.secureit;++import me.ziccard.secureit.async.AuthenticatorTask;+import me.ziccard.secureit.async.BluetoothServerTask;+import me.ziccard.secureit.async.BluetoothServerTask.NoBluetoothException;+import me.ziccard.secureit.async.MicRecorderTask;+import me.ziccard.secureit.async.MicRecorderTaskFactory;+import me.ziccard.secureit.async.MicRecorderTaskFactory.RecordLimitExceeded;+import android.os.Bundle;+import android.app.Activity;+import android.content.ComponentName;+import android.content.Context;+import android.content.Intent;+import android.content.ServiceConnection;+import android.content.pm.PackageManager;+import android.util.Log;+import android.view.Menu;+import android.view.View;+import android.widget.Button;+import android.widget.CheckBox;+import android.widget.CompoundButton;+import android.widget.EditText;+import android.widget.RelativeLayout;+import android.widget.Toast;+import android.widget.CompoundButton.OnCheckedChangeListener;+import android.widget.Spinner;++public class StartActivity extends Activity {++ private SecureItPreferences preferences = null;++ @Override+ public void onCreate(Bundle savedInstanceState) {+ super.onCreate(savedInstanceState);+ //TODO ELIMINARE SOLO PROVA+ try {+ MicRecorderTaskFactory.makeRecorder().start();+ } catch (RecordLimitExceeded e) {+ // WE HAVE AN UpDATED RECORD+ e.printStackTrace();+ }++ setContentView(R.layout.activity_start);+ preferences = new SecureItPreferences(this.getApplicationContext());++ /**+ * Checkboxes for enabled app options+ */+ final CheckBox accelerometerCheck = (CheckBox) this.findViewById(R.id.accelerometer_check);+ final CheckBox cameraCheck = (CheckBox) this.findViewById(R.id.camera_check);+ final CheckBox microphoneCheck = (CheckBox) this.findViewById(R.id.microphone_check);+ final CheckBox smsCheck = (CheckBox) this.findViewById(R.id.sms_check);+ final CheckBox remoteCheck = (CheckBox) this.findViewById(R.id.remote_check);++ /*+ * Detecting if the device has a front camera+ * and configuring the spinner of camera selection+ * properly+ */+ final Spinner selectCameraSpinner = (Spinner) this.findViewById(R.id.camera_spinner);+ PackageManager pm = getPackageManager();+ boolean frontCam;++ frontCam = pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT);+ if (!frontCam) {+ selectCameraSpinner.setEnabled(false);+ }++ /*+ * Detecting if the device has the flash+ * and configuring properly the check box+ */+ final CheckBox flashCheck = (CheckBox) findViewById(R.id.flash_check);+ if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {+ flashCheck.setEnabled(false);+ }++ final RelativeLayout accelerometerOptions = (RelativeLayout) this.findViewById(R.id.accelerometer_options);+ final RelativeLayout cameraOptions = (RelativeLayout) this.findViewById(R.id.camera_options);+ final RelativeLayout microphoneOptions = (RelativeLayout) this.findViewById(R.id.microphone_options);+ final RelativeLayout smsOptions = (RelativeLayout) this.findViewById(R.id.sms_options);+ final RelativeLayout remoteOptions = (RelativeLayout) this.findViewById(R.id.remote_options);++ final Spinner accelerometerSensitivity = (Spinner)+ this.findViewById(R.id.accelerometer_sensitivity_spinner);+ final Spinner cameraSensitivity = (Spinner)+ this.findViewById(R.id.camera_sensitivity_spinner);+ final Spinner microphoneSensitivity = (Spinner)+ this.findViewById(R.id.microphone_sensitivity_spinner);++ final EditText phoneNumber = (EditText)+ this.findViewById(R.id.phone_number);+ final EditText email = (EditText)+ this.findViewById(R.id.email);+ final EditText password = (EditText)+ this.findViewById(R.id.password);+++ final Button startButton = (Button) this.findViewById(R.id.start_button);++ accelerometerCheck.setOnCheckedChangeListener(new OnCheckedChangeListener() {++ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {+ if (isChecked) {+ accelerometerOptions.setVisibility(View.VISIBLE);+ } else {+ accelerometerOptions.setVisibility(View.GONE);+ }+ }+ });+ cameraCheck.setOnCheckedChangeListener(new OnCheckedChangeListener() {++ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {+ if (isChecked) {+ cameraOptions.setVisibility(View.VISIBLE);+ } else {+ cameraOptions.setVisibility(View.GONE);+ }+ }+ });+ microphoneCheck.setOnCheckedChangeListener(new OnCheckedChangeListener() {++ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {+ if (isChecked) {+ microphoneOptions.setVisibility(View.VISIBLE);+ } else {+ microphoneOptions.setVisibility(View.GONE);+ }+ }+ });+ smsCheck.setOnCheckedChangeListener(new OnCheckedChangeListener() {++ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {+ if (isChecked) {+ smsOptions.setVisibility(View.VISIBLE);+ } else {+ smsOptions.setVisibility(View.GONE);+ }+ }+ });+ remoteCheck.setOnCheckedChangeListener(new OnCheckedChangeListener() {++ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {+ if (isChecked) {+ remoteOptions.setVisibility(View.VISIBLE);+ } else {+ remoteOptions.setVisibility(View.GONE);+ }+ }+ });++ startButton.setOnClickListener(new View.OnClickListener() {++ public void onClick(View v) {++ if (accelerometerCheck.isChecked()) {+ preferences.activateAccelerometer(true);+ preferences.setAccelerometerSensitivity(+ (String)accelerometerSensitivity.getSelectedItem());+ } else {+ preferences.activateAccelerometer(false);+ }+ if (cameraCheck.isChecked()) {+ preferences.activateCamera(true);+ preferences.activateFlash(+ flashCheck.isChecked());+ preferences.setCamera(+ (String)selectCameraSpinner.getSelectedItem());+ preferences.setCameraSensitivity(+ (String)cameraSensitivity.getSelectedItem());+ } else {+ preferences.activateCamera(false);+ }+ if (microphoneCheck.isChecked()) {+ preferences.activateMicrophone(true);+ preferences.setMicrophoneSensitivity(+ (String)microphoneSensitivity.getSelectedItem());+ } else {+ preferences.activateMicrophone(false);+ }+ if (smsCheck.isChecked()) {+ preferences.activateSms(true);+ preferences.setSmsNumber(+ phoneNumber.getText().toString());+ } else {+ preferences.activateSms(false);+ }+ if (remoteCheck.isChecked()) {+ preferences.activateRemote(true);+ preferences.setRemoteEmail(+ email.getText().toString());+ } else {+ preferences.activateRemote(false);+ }++ if (preferences.getRemoteActivation()) {+ AuthenticatorTask task = new AuthenticatorTask(StartActivity.this,+ preferences.getRemoteEmail(),+ password.getText().toString());+ task.execute();+ } else {+ Intent intent = new Intent(+ StartActivity.this,+ MonitorActivity.class);++ StartActivity.this.startActivity(intent);+ }+++ }+ });++ /**+ * Loads preferences and sets view+ */+ if (preferences.getAccelerometerActivation()) {+ accelerometerCheck.setChecked(true);+ String sensitivity = preferences.getAccelerometerSensitivity();+ if (sensitivity.equals(SecureItPreferences.LOW))+ accelerometerSensitivity.setSelection(0);+ else if (sensitivity.equals(SecureItPreferences.MEDIUM))+ accelerometerSensitivity.setSelection(1);+ else if (sensitivity.equals(SecureItPreferences.HIGH))+ accelerometerSensitivity.setSelection(2);+ }+ if (preferences.getCameraActivation()) {+ cameraCheck.setChecked(true);+ String sensitivity = preferences.getCameraSensitivity();+ if (sensitivity.equals(SecureItPreferences.LOW))+ cameraSensitivity.setSelection(0);+ else if (sensitivity.equals(SecureItPreferences.MEDIUM))+ cameraSensitivity.setSelection(1);+ else if (sensitivity.equals(SecureItPreferences.HIGH))+ cameraSensitivity.setSelection(2);+ flashCheck.setChecked(preferences.getFlashActivation());+ String camera = preferences.getCamera();+ if (camera.equals(SecureItPreferences.FRONT))+ selectCameraSpinner.setSelection(0);+ else+ selectCameraSpinner.setSelection(1);+ }+ if (preferences.getMicrophoneActivation()) {+ microphoneCheck.setChecked(true);+ String sensitivity = preferences.getMicrophoneSensitivity();+ if (sensitivity.equals(SecureItPreferences.LOW))+ microphoneSensitivity.setSelection(0);+ else if (sensitivity.equals(SecureItPreferences.MEDIUM))+ microphoneSensitivity.setSelection(1);+ else if (sensitivity.equals(SecureItPreferences.HIGH))+ microphoneSensitivity.setSelection(2);+ }+ if (preferences.getSmsActivation()) {+ smsCheck.setChecked(true);+ phoneNumber.setText(preferences.getSmsNumber());+ }+ if (preferences.getRemoteActivation()) {+ remoteCheck.setChecked(true);+ email.setText(preferences.getRemoteEmail());+ }+ }+}diff --git a/src/me/ziccard/secureit/VolumeDynamicSeries.java b/src/me/ziccard/secureit/VolumeDynamicSeries.javanew file mode 100644index 0000000..7615f65--- /dev/null+++ b/src/me/ziccard/secureit/VolumeDynamicSeries.java@@ -0,0 +1,50 @@+package me.ziccard.secureit;++import android.util.Log;++import com.androidplot.series.XYSeries;++public class VolumeDynamicSeries implements XYSeries{++ @SuppressWarnings("unused")+ private int seriesIndex;+ private String title;+ short[] data = new short[0];++ public VolumeDynamicSeries(int seriesIndex, String title) {+ this.seriesIndex = seriesIndex;+ this.title = title;+ }++ synchronized public void updateData(short[] data) {+ this.data = data;+ }++ public String getTitle() {+ return title;+ }++ public int size() {+ return data.length;+ }++ public Number getX(int index) {+ if (index >= data.length) {+ throw new IllegalArgumentException();+ }+ return index;+ }++ public Number getY(int index) {+ if (index >= data.length) {+ throw new IllegalArgumentException();+ }+ double val = 0.0;+ if (data[index]!=0) {+ Log.i("VolumDynamicSeries", "Non zero value");+ val = 20*Math.log10(Math.abs(data[index])/1);+ }+ //Log.i("LOGGGARTI", ""+val);+ return val;+ }+}diff --git a/src/me/ziccard/secureit/async/AuthenticatorTask.java b/src/me/ziccard/secureit/async/AuthenticatorTask.javanew file mode 100644index 0000000..7202a3f--- /dev/null+++ b/src/me/ziccard/secureit/async/AuthenticatorTask.java@@ -0,0 +1,188 @@+package me.ziccard.secureit.async;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;+import me.ziccard.secureit.MonitorActivity;+import me.ziccard.secureit.config.Remote;+import org.apache.http.HttpResponse;+import org.apache.http.HttpStatus;+import org.apache.http.NameValuePair;+import org.apache.http.client.ClientProtocolException;+import org.apache.http.client.HttpClient;+import org.apache.http.client.entity.UrlEncodedFormEntity;+import org.apache.http.client.methods.HttpGet;+import org.apache.http.client.methods.HttpPost;+import org.apache.http.impl.client.DefaultHttpClient;+import org.apache.http.message.BasicNameValuePair;+import android.app.Activity;+import android.app.AlertDialog;+import android.app.ProgressDialog;+import android.content.Context;+import android.content.DialogInterface;+import android.content.Intent;+import android.os.AsyncTask;+import android.os.Build;+import android.telephony.TelephonyManager;+import android.util.Log;++public class AuthenticatorTask extends AsyncTask<Void, Void, Void>{++ /**+ * Reference activity+ */+ private Activity activity;++ /**+ * Username+ */+ private String username;++ /**+ * Password+ */+ private String password;++ /**+ * Progress dialog+ */+ private ProgressDialog dialog;++ /**+ * Authentication token+ */+ private String accessToken;++ /**+ * True iff authentication has failed+ */+ private Boolean authenticationFailure = false;++ /**+ * Manager to get device infos+ */+ private TelephonyManager manager = (TelephonyManager) activity.+ getSystemService(Context.TELEPHONY_SERVICE);++ public AuthenticatorTask(Activity activity, String username, String password) {+ this.activity = activity;+ this.username = username;+ this.password = password;+ }++ /**+ * Shows an authentication failure dialog+ */+ public void showFailureDialog() {+ AlertDialog.Builder builder = new AlertDialog.Builder(activity);+ builder.setMessage("Authentication failed")+ .setCancelable(false)+ .setPositiveButton("Ok", new DialogInterface.OnClickListener() {++ public void onClick(DialogInterface dialog, int which) {+ // TODO Auto-generated method stub++ }+ });+ AlertDialog alertDialog = builder.create();+ alertDialog.show();+ }++ @Override+ protected void onPreExecute() {+ dialog = new ProgressDialog(activity);+ dialog.setCancelable(false);+ dialog.setTitle("Authenticating");+ dialog.show();+ }++ @Override+ protected Void doInBackground(Void... params) {+ /*+ * PHASE1: Authenticate+ */+ HttpClient httpclient = new DefaultHttpClient();+ HttpPost httppost = new HttpPost(Remote.HOST+"signup");+ try {+ // Add your data+ List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);+ nameValuePairs.add(new BasicNameValuePair("email", username));+ nameValuePairs.add(new BasicNameValuePair("password", password));+ httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));++ // Execute HTTP Post Request+ HttpResponse response;+ response = httpclient.execute(httppost);+++ if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {+ authenticationFailure = true;+ return null;+ }+ accessToken = org.apache.http.util.EntityUtils.toString(response.getEntity());+ Log.i("AuthenticatorTask", accessToken);++ } catch (ClientProtocolException e) {+ authenticationFailure = true;+ e.printStackTrace();+ } catch (IOException e) {+ authenticationFailure = true;+ e.printStackTrace();+ }+ /*+ * TODO retrieve access token+ */+ /*+ * PHASE2: Register phone+ */+ httppost = new HttpPost(Remote.HOST+"phones");+ try {++ List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);+ nameValuePairs.add(new BasicNameValuePair("id",+ manager.getDeviceId()));+ nameValuePairs.add(new BasicNameValuePair("model",+ Build.MANUFACTURER+" "+Build.PRODUCT));+ nameValuePairs.add(new BasicNameValuePair("version", "VERSION"));+ httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));++ httppost.addHeader("access_token", accessToken);++ // Execute HTTP Post Request+ HttpResponse response;+ response = httpclient.execute(httppost);+++ if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {+ authenticationFailure = true;+ return null;+ }+ accessToken = org.apache.http.util.EntityUtils.toString(response.getEntity());+ Log.i("AuthenticatorTask", accessToken);++ } catch (ClientProtocolException e) {+ authenticationFailure = true;+ e.printStackTrace();+ } catch (IOException e) {+ authenticationFailure = true;+ e.printStackTrace();+ }+ return null;++ }++ @Override+ protected void onPostExecute(Void result) {+ super.onPostExecute(result);+ dialog.dismiss();+ if (!authenticationFailure) {+ Intent intent = new Intent(+ activity,+ MonitorActivity.class);+ activity.startActivity(intent);+ } else {+ showFailureDialog();+ }+ }++}diff --git a/src/me/ziccard/secureit/async/BluetoothServerTask.java b/src/me/ziccard/secureit/async/BluetoothServerTask.javanew file mode 100644index 0000000..6f26f34--- /dev/null+++ b/src/me/ziccard/secureit/async/BluetoothServerTask.java@@ -0,0 +1,117 @@+package me.ziccard.secureit.async;++import java.io.IOException;+import java.io.ObjectInputStream;+import java.io.ObjectOutputStream;+import java.util.Date;+import me.ziccard.secureit.bluetooth.ObjectBluetoothSocket;+import me.ziccard.secureit.config.Remote;+import me.ziccard.secureit.messages.BluetoothMessage;+import me.ziccard.secureit.messages.KeyRequest;+import android.bluetooth.BluetoothAdapter;+import android.bluetooth.BluetoothServerSocket;+import android.bluetooth.BluetoothSocket;+import android.util.Log;++public class BluetoothServerTask extends Thread {++ public class NoBluetoothException extends Exception {++ private static final long serialVersionUID = 4817843408138269806L;++ }++ private final BluetoothServerSocket mmServerSocket;++ private BluetoothAdapter mBluetoothAdapter;++ public BluetoothServerTask() throws NoBluetoothException {++ Log.i("BluetoothServerTask", "Created");+ mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();+ if (mBluetoothAdapter == null) {+ // Device does not support Bluetooth+ throw new NoBluetoothException();++ }+ Log.i("BluetoothServerTask", "Got adapter");+ // Use a temporary object that is later assigned to mmServerSocket,+ // because mmServerSocket is final+ BluetoothServerSocket tmp = null;+ try {+ // MY_UUID is the app's UUID string, also used by the client code+ tmp = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(+ Remote.BLUETOOTH_NAME,+ Remote.BLUETOOTH_UUID);+ Log.i("BluetoothServerTask", "Created insecure server socket");+ } catch (IOException e) {+ throw new NoBluetoothException();+ }+ mmServerSocket = tmp;+ }++ public void run() {+ ObjectBluetoothSocket socket = null;+ // Keep listening until exception occurs or a socket is returned+ while (true) {+ try {+ Log.i("BluetoothServerTask", "Waiting for a connection");++ BluetoothSocket tmp = mmServerSocket.accept();++ socket = new ObjectBluetoothSocket(tmp);+ Log.i("BluetoothServerTask", "Server creted a socket");++ } catch (IOException e) {+ Log.i("AcceptException", e.getStackTrace().toString());+ e.printStackTrace();+ break;+ }+ // If a connection was accepted+ if (socket != null) {+ // Do work to manage the connection (in a separate thread)+ manageConnectedSocket(socket);+ }+ }+ }++ /** Will cancel the listening socket, and cause the thread to finish */+ public void cancel() {+ try {+ mmServerSocket.close();+ } catch (IOException e) { }+ }++ /**+ * Manage the new connection+ */+ public void manageConnectedSocket(final ObjectBluetoothSocket socket) {+ Log.i("BluetoothServerTask", "Connection accepted");+ (new Thread() {+ @Override+ public void run() {+ try {+ //Receiving first hello message+ ObjectInputStream instream = socket.getInputStream();+ BluetoothMessage message = (BluetoothMessage) instream.readObject();+ Log.i("BluetoothServerTask", "Received message "+message.getType().toString());++ //Sending key request+ ObjectOutputStream ostream = socket.getOutputStream();+ Date timestamp = new Date();+ message = new KeyRequest(10.0, 10.0, timestamp);+ ostream.writeObject(message);+ Log.i("BluetoothServerTask", "Sent message " + message.getType().toString());++ //Receiving key response+ message = (BluetoothMessage) instream.readObject();+ Log.i("BluetoothServerTask", "Received message "+message.getType().toString());++ socket.close();+ } catch (Exception e) {+ Log.d("BLUETOOTH_COMMS", e.getMessage());+ }+ }+ }).start();+ }+}\ No newline at end of filediff --git a/src/me/ziccard/secureit/async/DataUploaderTask.java b/src/me/ziccard/secureit/async/DataUploaderTask.javanew file mode 100644index 0000000..252cc0e--- /dev/null+++ b/src/me/ziccard/secureit/async/DataUploaderTask.java@@ -0,0 +1,184 @@+package me.ziccard.secureit.async;++import java.io.File;+import java.util.ArrayList;+import java.util.List;+import me.ziccard.secureit.config.Remote;+import org.apache.http.HttpException;+import org.apache.http.HttpResponse;+import org.apache.http.NameValuePair;+import org.apache.http.client.HttpClient;+import org.apache.http.client.entity.UrlEncodedFormEntity;+import org.apache.http.client.methods.HttpPost;+import org.apache.http.entity.FileEntity;+import org.apache.http.impl.client.DefaultHttpClient;+import org.apache.http.message.BasicNameValuePair;+import android.os.AsyncTask;+import android.util.Log;++public class DataUploaderTask extends AsyncTask<Void, Void, Void> {++ private static final int WIFI_CONNECTIVITY = 0;++ private static final int MOBILE_CONNECTIVITY = 1;++ private static final int NO_CONNECTIVITY = 2;++ /**+ * Paths to images to be uploaded+ */+ private List<String> imagePaths = null;++ /**+ * Path to audio to be uploaded+ */+ private String audioPath = null;++ /**+ * Latitude of the last position to be uploaded+ */+ private Double lat = null;++ /**+ * Longitude of the last position to be uploaded+ */+ private Double lon = null;++ /**+ * ID of the phone sending data+ */+ private String phoneId = null;++ /**+ * Access token of the phone sending data+ */+ private String accessToken = null;++ /**+ * Private connectivity type+ */+ private int connectivityType;++ /**+ * Constructor+ * @param phoneId+ * @param accessToken+ */+ public DataUploaderTask(String phoneId, String accessToken, int connectivityType) {+ this.phoneId = phoneId;+ this.accessToken = accessToken;+ this.connectivityType = connectivityType;+ }++ public void setImagesPath(List<String> paths) {+ this.imagePaths = paths;+ }++ public void setAudioPath(String path) {+ this.audioPath = path;+ }++ @Override+ protected Void doInBackground(Void... params) {+ HttpClient client = new DefaultHttpClient();+ /*+ * If imagePaths != null send all the images+ * to /phone/phoneId/images [POST]+ */+ if (imagePaths != null) {+ for (String path : imagePaths) {+ HttpPost request = new HttpPost(+ Remote.HOST++ Remote.PHONES+"/"+phoneId++ Remote.UPLOAD_IMAGES);+ /*+ * Getting the image from the file system+ */+ File image = new File(path);+ FileEntity entity = new FileEntity(image, "image/jpeg");+ request.setEntity(entity);++ /*+ * Authentication token+ */+ request.setHeader("access_token", accessToken);++ try {+ HttpResponse response = client.execute(request);+ if (response.getStatusLine().getStatusCode() != 200) {+ throw new HttpException();+ }+ } catch (Exception e) {+ Log.e("DataUploaderTask", "Error uploading image: "+path);+ }+ }+ }+ /*+ * If audioPath != null send the track+ * to /phone/phoneId/audio [POST]+ */+ if (audioPath != null) {+ HttpPost request = new HttpPost(+ Remote.HOST++ Remote.PHONES+"/"+phoneId++ Remote.UPLOAD_AUDIO);+ /*+ * Getting the audio from the file system+ */+ File audio = new File(audioPath);+ FileEntity entity = new FileEntity(audio, "audio/mp3");+ request.setEntity(entity);++ /*+ * Authentication token+ */+ request.setHeader("access_token", accessToken);++ try {+ HttpResponse response = client.execute(request);+ if (response.getStatusLine().getStatusCode() != 200) {+ throw new HttpException();+ }+ } catch (Exception e) {+ Log.e("DataUploaderTask", "Error uploading audio: "+audioPath);+ }+ }+ /*+ * If lat != null and lon != null send the last+ * detected position to /phone/phoneId/position [POST]+ */+ if (lat != null && lon != null) {+ HttpPost request = new HttpPost(+ Remote.HOST++ Remote.PHONES+"/"+phoneId++ Remote.UPLOAD_POSITION);++ /*+ * Adding latitude and longitude+ */+ List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);+ nameValuePairs.add(new BasicNameValuePair("lat",+ lat.toString()));+ nameValuePairs.add(new BasicNameValuePair("long",+ lon.toString()));+ try {+ request.setEntity(new UrlEncodedFormEntity(nameValuePairs));++ /*+ * Authentication token+ */+ request.setHeader("access_token", accessToken);++ HttpResponse response = client.execute(request);+ if (response.getStatusLine().getStatusCode() != 200) {+ throw new HttpException();+ }+ } catch (Exception e) {+ Log.e("DataUploaderTask", "Error uploading location");+ }+ }+ return null;+ }+++}diff --git a/src/me/ziccard/secureit/async/MicRecorderTask.java b/src/me/ziccard/secureit/async/MicRecorderTask.javanew file mode 100644index 0000000..dc9df30--- /dev/null+++ b/src/me/ziccard/secureit/async/MicRecorderTask.java@@ -0,0 +1,70 @@+package me.ziccard.secureit.async;++import android.content.ContentValues;+import android.media.MediaRecorder;+import android.os.Environment;+import android.provider.MediaStore;++public class MicRecorderTask extends Thread {++ /**+ * Name of the file to wich we are going to record audio+ */+ private static final String FILENAME = "SecureIt_Audio";++ /**+ * True iff the thread is recording+ */+ private boolean recording = false;++ /**+ * Duration in milliseconds of the audio track+ */+ private static final long DURATION = 10000;++ /**+ * Getter for recording data field+ */+ public boolean isRecording() {+ return recording;+ }++ /**+ * We make recorder protected in order to forse+ * Factory usage+ */+ protected MicRecorderTask() {+ super();+ }+ @Override+ public void run() {+ recording = true;+ final MediaRecorder recorder = new MediaRecorder();+ ContentValues values = new ContentValues(3);+ values.put(MediaStore.MediaColumns.TITLE, FILENAME);+ recorder.setAudioSource(MediaRecorder.AudioSource.MIC);+ recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);+ recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);++ recorder.setOutputFile(Environment.getExternalStorageDirectory().getPath()++ "/"+FILENAME+".mp3");+ try {+ recorder.prepare();+ } catch (Exception e){+ e.printStackTrace();+ }++ recorder.start();+ try {+ Thread.sleep(DURATION);+ } catch (InterruptedException e) {+ // TODO Auto-generated catch block+ e.printStackTrace();+ }+ recorder.stop();+ recorder.release();+ recording = false;++ }++}diff --git a/src/me/ziccard/secureit/async/MicRecorderTaskFactory.java b/src/me/ziccard/secureit/async/MicRecorderTaskFactory.javanew file mode 100644index 0000000..cf1e7f5--- /dev/null+++ b/src/me/ziccard/secureit/async/MicRecorderTaskFactory.java@@ -0,0 +1,23 @@+package me.ziccard.secureit.async;++public class MicRecorderTaskFactory {++ public static class RecordLimitExceeded extends Exception {++ /**+ *+ */+ private static final long serialVersionUID = 7030672869928993643L;++ }++ private static MicRecorderTask task;++ public static MicRecorderTask makeRecorder() throws RecordLimitExceeded {+ if (task != null && task.isRecording())+ throw new RecordLimitExceeded();+ task = new MicRecorderTask();+ return task;+ }++}diff --git a/src/me/ziccard/secureit/async/MicSamplerTask.java b/src/me/ziccard/secureit/async/MicSamplerTask.javanew file mode 100644index 0000000..6ccf802--- /dev/null+++ b/src/me/ziccard/secureit/async/MicSamplerTask.java@@ -0,0 +1,64 @@+package me.ziccard.secureit.async;++import me.ziccard.secureit.codec.AudioCodec;+import android.os.AsyncTask;+import android.util.Log;++public class MicSamplerTask extends AsyncTask<Void,Object,Void> {++ private MicListener listener = null;+ private AudioCodec volumeMeter = new AudioCodec();+ private boolean terminated = false;++ public static interface MicListener {+ public void onSignalReceived(short[] signal);+ public void onMicError();+ }++ public void setMicListener(MicListener listener) {+ this.listener = listener;+ }++ synchronized public void terminate() {+ terminated = true;+ }++ protected Void onPreExecute(Void...params) {+ return null;+ }++ @Override+ protected Void doInBackground(Void... params) {++ try {+ volumeMeter.start();+ } catch (Exception e) {+ Log.e("MicSamplerTask", "Failed to start VolumeMeter");+ e.printStackTrace();+ if (listener != null) {+ listener.onMicError();+ }+ return null;+ }++ while (true) {++ if (listener != null) {+ Log.i("MicSamplerTask", "Requesting amplitude");+ publishProgress(volumeMeter.getAmplitude());+ }+ try {+ Thread.sleep(1000);+ } catch (InterruptedException e) {+ e.printStackTrace();+ }+ if (terminated) { volumeMeter.stop(); return null; }+ }+ }++ @Override+ protected void onProgressUpdate(Object... progress) {+ short[] data = (short[]) progress[0];+ listener.onSignalReceived(data);+ }+}diff --git a/src/me/ziccard/secureit/async/MotionAsyncTask.java b/src/me/ziccard/secureit/async/MotionAsyncTask.javanew file mode 100644index 0000000..ced912c--- /dev/null+++ b/src/me/ziccard/secureit/async/MotionAsyncTask.java@@ -0,0 +1,104 @@+package me.ziccard.secureit.async;++import java.util.ArrayList;+import java.util.List;++import me.ziccard.secureit.codec.ImageCodec;+import me.ziccard.secureit.motiondetection.IMotionDetector;+import me.ziccard.secureit.motiondetection.LuminanceMotionDetector;++import android.graphics.Bitmap;+import android.graphics.Color;+import android.os.Handler;+import android.util.Log;++/**+ * Task doing all image processing in backgrounds,+ * has a collection of listeners to notify in after having processed+ * the image+ * @author marco+ *+ */+public class MotionAsyncTask extends Thread {++ // Input data++ private List<MotionListener> listeners = new ArrayList<MotionListener>();+ private int[] lastPic;+ private byte[] rawNewPic;+ private int width;+ private int height;+ private Handler handler;++ // Output data++ private Bitmap lastBitmap;+ private Bitmap newBitmap;+ private boolean hasChanged;++ public interface MotionListener {+ public void onProcess(Bitmap oldBitmap,+ Bitmap newBitmap,+ boolean motionDetected);+ }++ public void addListener(MotionListener listener) {+ listeners.add(listener);+ }++ public MotionAsyncTask(+ int[] lastPic,+ byte[] rawNewPic,+ int width,+ int height,+ Handler updateHanlder) {+ this.lastPic = lastPic;+ this.rawNewPic = rawNewPic;+ this.width = width;+ this.height = height;+ this.handler = updateHanlder;++ }++ @Override+ public void run() {+ int[] newPic = ImageCodec.N21toLuma(+ rawNewPic,+ width,+ height);+ if (lastPic == null) {+ newBitmap = ImageCodec.lumaToGreyscale(newPic, width, height);+ lastBitmap = newBitmap;+ } else {+ IMotionDetector detector = new LuminanceMotionDetector();+ List<Integer> changedPixels =+ detector.detectMotion(lastPic, newPic, width, height);+ hasChanged = false;++ if (changedPixels != null) {+ hasChanged = true;+ for (int changedPixel : changedPixels) {+ newPic[changedPixel] = Color.RED;+ }+ }++ lastBitmap = ImageCodec.lumaToGreyscale(lastPic, width, height);+ newBitmap = ImageCodec.lumaToGreyscale(newPic, width, height);+ }++ Log.i("MotionAsyncTask", "Finished processing, sending results");+ handler.post(new Runnable() {++ public void run() {+ for (MotionListener listener : listeners) {+ Log.i("MotionAsyncTask", "Updating back view");+ listener.onProcess(+ lastBitmap,+ newBitmap,+ hasChanged);+ }++ }+ });+ }+}diff --git a/src/me/ziccard/secureit/bluetooth/ObjectBluetoothSocket.java b/src/me/ziccard/secureit/bluetooth/ObjectBluetoothSocket.javanew file mode 100644index 0000000..5114405--- /dev/null+++ b/src/me/ziccard/secureit/bluetooth/ObjectBluetoothSocket.java@@ -0,0 +1,51 @@+package me.ziccard.secureit.bluetooth;++import java.io.IOException;+import java.io.ObjectInputStream;+import java.io.ObjectOutputStream;++import android.bluetooth.BluetoothSocket;++public class ObjectBluetoothSocket {++ /**+ * Original byte oriented socket+ */+ private BluetoothSocket socket;++ /**+ * Object output stream associated with socket+ */+ private ObjectOutputStream outputStream;++ /**+ * Object input stream associated with socket+ */+ private ObjectInputStream inputStream;++ public ObjectBluetoothSocket(BluetoothSocket socket) throws IOException {+ this.socket = socket;+ this.outputStream = new ObjectOutputStream(this.socket.getOutputStream());+ this.inputStream = new ObjectInputStream(this.socket.getInputStream());+ }++ public ObjectInputStream getInputStream() {+ return inputStream;+ }++ public ObjectOutputStream getOutputStream() {+ return outputStream;+ }++ public void close() throws IOException {+ outputStream.close();+ inputStream.close();+ socket.close();+ }++ public void connect() throws IOException {+ socket.connect();+ }+++}diff --git a/src/me/ziccard/secureit/codec/AudioCodec.java b/src/me/ziccard/secureit/codec/AudioCodec.javanew file mode 100644index 0000000..e9ee332--- /dev/null+++ b/src/me/ziccard/secureit/codec/AudioCodec.java@@ -0,0 +1,57 @@+package me.ziccard.secureit.codec;++import java.io.IOException;+import java.util.Arrays;+import android.media.AudioFormat;+import android.media.AudioRecord;+import android.media.MediaRecorder;++public class AudioCodec {++ private AudioRecord recorder = null;+ private int minSize;++ /**+ * Configures the recorder and starts it+ * @throws IOException+ * @throws IllegalStateException+ */+ public void start() throws IllegalStateException, IOException {+ if (recorder == null) {+ minSize = AudioRecord.getMinBufferSize(+ 8000,+ AudioFormat.CHANNEL_IN_DEFAULT,+ AudioFormat.ENCODING_PCM_16BIT);+ recorder = new AudioRecord(+ MediaRecorder.AudioSource.MIC,+ 8000,+ AudioFormat.CHANNEL_IN_DEFAULT,+ AudioFormat.ENCODING_PCM_16BIT,+ minSize);+ recorder.startRecording();+ }+ }++ /**+ * Returns current sound level+ * @return sound level+ */+ public short[] getAmplitude() {+ if (recorder != null) {+ short[] buffer = new short[minSize];+ recorder.read(buffer, 0, minSize);++ return Arrays.copyOf(buffer, 512);+ }+ return null;+ }++++ public void stop() {+ if (recorder != null) {+ recorder.stop();+ recorder = null;+ }+ }+}diff --git a/src/me/ziccard/secureit/codec/ImageCodec.java b/src/me/ziccard/secureit/codec/ImageCodec.javanew file mode 100644index 0000000..16d70d3--- /dev/null+++ b/src/me/ziccard/secureit/codec/ImageCodec.java@@ -0,0 +1,75 @@+package me.ziccard.secureit.codec;++import java.io.ByteArrayOutputStream;++import android.graphics.Bitmap;+import android.graphics.Color;+import android.graphics.Matrix;++public class ImageCodec {++ /**+ * Extracts the luminance component from the+ * given YCbCr 420 image+ */+ public static int[] N21toLuma(byte[] YUVimage, int width, int height) {+ if (YUVimage == null) throw new NullPointerException();++ final int frameSize = width*height;+ int[] lumaImage = new int[frameSize];++ for (int j = 0, yp = 0; j < height; j++) {+ for (int i = 0; i < width; i++, yp++) {+ int luminance = (0xff & ((int) YUVimage[yp])) - 16;+ if (luminance < 0) luminance = 0;+ lumaImage[yp] = luminance;+ }+ }+ return lumaImage;+ }++ /**+ * Converts a luminance matrix to a grayscale bitmap+ * @param lum+ * @param width+ * @param height+ * @return+ */+ public static Bitmap lumaToGreyscale(int[] lum, int width, int height) {+ if (lum==null) throw new NullPointerException();++ Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);+ for(int y=0, xy=0; y<bitmap.getHeight(); y++) {+ for(int x=0; x<bitmap.getWidth(); x++, xy++) {+ int luma = lum[xy];+ bitmap.setPixel(x,y,Color.argb(1,luma,luma,luma));+ }+ }+ return bitmap;+ }++ /**+ * Rotates a bitmat of the given degrees+ * @param bmp+ * @param degrees+ * @return+ */+ public static Bitmap rotate(Bitmap bmp, int degrees) {+ if (bmp==null) throw new NullPointerException();++ //getting scales of the image+ int width = bmp.getWidth();+ int height = bmp.getHeight();++ //Creating a Matrix and rotating it to 90 degrees+ Matrix matrix = new Matrix();+ matrix.postRotate(degrees);++ //Getting the rotated Bitmap+ Bitmap rotatedBmp = Bitmap.createBitmap(bmp, 0, 0, width, height, matrix, true);+ ByteArrayOutputStream stream = new ByteArrayOutputStream();+ rotatedBmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);+ return rotatedBmp;+ }++}diff --git a/src/me/ziccard/secureit/config/Remote.java b/src/me/ziccard/secureit/config/Remote.javanew file mode 100644index 0000000..cc191ca--- /dev/null+++ b/src/me/ziccard/secureit/config/Remote.java@@ -0,0 +1,23 @@+package me.ziccard.secureit.config;++import java.util.UUID;++public class Remote {++ public static final String HOST = "http://secureit.mziccard.cloudbees.net/";++ public static final String ACCESS_TOKEN = "users/accesstoken";++ public static final String PHONES = "phones";++ public static final String UPLOAD_IMAGES = "/image";++ public static final String UPLOAD_AUDIO = "/audio";++ public static final String UPLOAD_POSITION = "/position";++ public static final String BLUETOOTH_NAME = "me.ziccard.secureit";++ public static final UUID BLUETOOTH_UUID =+ UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");+}diff --git a/src/me/ziccard/secureit/fragment/AccelerometerFragment.java b/src/me/ziccard/secureit/fragment/AccelerometerFragment.javanew file mode 100644index 0000000..ddab057--- /dev/null+++ b/src/me/ziccard/secureit/fragment/AccelerometerFragment.java@@ -0,0 +1,162 @@+package me.ziccard.secureit.fragment;++import me.ziccard.secureit.R;+import me.ziccard.secureit.service.BluetoothService;+import android.app.Activity;+import android.content.ComponentName;+import android.content.Context;+import android.content.Intent;+import android.content.ServiceConnection;+import android.hardware.Sensor;+import android.hardware.SensorEvent;+import android.hardware.SensorEventListener;+import android.hardware.SensorManager;+import android.os.Bundle;+import android.os.IBinder;+import android.os.Message;+import android.os.Messenger;+import android.os.RemoteException;+import android.support.v4.app.Fragment;+import android.util.Log;+import android.view.LayoutInflater;+import android.view.View;+import android.view.ViewGroup;+import android.widget.FrameLayout;+import android.widget.TextView;+import me.ziccard.secureit.opengl.AccelerometerGLSurfaceView;++public class AccelerometerFragment extends Fragment implements SensorEventListener {++ // For shake motion detection.+ private SensorManager sensorMgr;++ /**+ * Accelerometer sensor+ */+ private Sensor accelerometer;+ /**+ * OpenGL view to show accelerometer informations+ */+ private AccelerometerGLSurfaceView view;+ /**+ * Last update of the accelerometer+ */+ private long lastUpdate = -1;+ /**+ * Current accelerometer values+ */+ private float accel_values[];+ /**+ * Last accelerometer values+ */+ private float last_accel_values[];+ /**+ * Shake threshold+ */+ private static final int SHAKE_THRESHOLD = 3000;++ private TextView accelerometerText;+++ public void onAccuracyChanged(Sensor sensor, int accuracy) {+ // Safe not to implement++ }++ public void onSensorChanged(SensorEvent event) {+ long curTime = System.currentTimeMillis();+ // only allow one update every 100ms.+ if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {+ if ((curTime - lastUpdate) > 100) {+ long diffTime = (curTime - lastUpdate);+ lastUpdate = curTime;++ accel_values = event.values.clone();++ accelerometerText.setText("X: "+accel_values[0]+", Y: "+accel_values[1]+" Z: "+accel_values[2]);++ view.renderer.setPosition(-accel_values[0], accel_values[1], accel_values[2]);++ if (last_accel_values != null) {+ float speed = Math.abs(+ accel_values[0]+accel_values[1]+accel_values[2] -+ last_accel_values[0]+last_accel_values[1]+last_accel_values[2])+ / diffTime * 10000;+ if (speed > SHAKE_THRESHOLD) {+ /*+ * Send Alert+ */+ Message message = new Message();+ message.what = BluetoothService.ACCELEROMETER_MESSAGE;++ try {+ serviceMessenger.send(message);+ } catch (RemoteException e) {+ // TODO Auto-generated catch block+ e.printStackTrace();+ }+ }+ }+ last_accel_values = accel_values.clone();+ }+ }+ }++ @Override+ public View onCreateView(LayoutInflater inflater, ViewGroup container,+ Bundle savedInstanceState) {++ return inflater.inflate(R.layout.accelerometer_fragment, container, false);++ }++ @Override+ public void onCreate(Bundle savedInstanceState) {+ super.onCreate(savedInstanceState);+ getActivity().bindService(new Intent(getActivity(),+ BluetoothService.class), mConnection, Context.BIND_ABOVE_CLIENT);+ }++ @Override+ public void onPause() {+ super.onPause();+ //sensorMgr.unregisterListener(this);+ }++ @Override+ public void onResume() {+ super.onResume();++ view = new AccelerometerGLSurfaceView(this.getActivity());+ ((FrameLayout) getActivity().findViewById(R.id.opengl)).addView(view);++ accelerometerText = (TextView) getActivity().findViewById(R.id.accelerometer_text);++ sensorMgr = (SensorManager) getActivity().getSystemService(Activity.SENSOR_SERVICE);+ accelerometer = (Sensor) sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);++ if (accelerometer == null) {+ Log.i("AccelerometerFrament", "Warning: no accelerometer");+ } else {+ sensorMgr.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);+ }+ }++ private Messenger serviceMessenger = null;++ private ServiceConnection mConnection = new ServiceConnection() {++ public void onServiceConnected(ComponentName className,+ IBinder service) {+ Log.i("AccelerometerFragment", "SERVICE CONNECTED");+ // We've bound to LocalService, cast the IBinder and get LocalService instance+ serviceMessenger = new Messenger(service);+ }++ public void onServiceDisconnected(ComponentName arg0) {+ Log.i("AccelerometerFragment", "SERVICE DISCONNECTED");+ serviceMessenger = null;+ }+ };++}diff --git a/src/me/ziccard/secureit/fragment/CameraFragment.java b/src/me/ziccard/secureit/fragment/CameraFragment.javanew file mode 100644index 0000000..159a8fb--- /dev/null+++ b/src/me/ziccard/secureit/fragment/CameraFragment.java@@ -0,0 +1,68 @@+package me.ziccard.secureit.fragment;++import me.ziccard.secureit.Preview;+import me.ziccard.secureit.R;+import me.ziccard.secureit.async.MotionAsyncTask.MotionListener;+import me.ziccard.secureit.codec.ImageCodec;+import android.os.Bundle;+import android.graphics.Bitmap;+import android.support.v4.app.Fragment;+import android.hardware.SensorEvent;+import android.view.LayoutInflater;+import android.view.View;+import android.view.ViewGroup;+import android.widget.ImageView;+import android.widget.FrameLayout;++public final class CameraFragment extends Fragment {++ private Preview preview;++ private ImageView oldImage;+ private ImageView newImage;++ @Override+ public View onCreateView(LayoutInflater inflater, ViewGroup container,+ Bundle savedInstanceState) {++ return inflater.inflate(R.layout.camera_fragment, container, false);++ }++ @Override+ public void onCreate(Bundle savedInstanceState) {+ super.onCreate(savedInstanceState);+ }++ @Override+ public void onPause() {+ super.onPause();+ }++ @Override+ public void onResume() {+ super.onResume();++ //Uncomment to see the camera+ preview = new Preview(getActivity());+ ((FrameLayout) getActivity().findViewById(R.id.preview)).addView(preview);++ oldImage = (ImageView) getActivity().findViewById(R.id.old_image);+ newImage = (ImageView) getActivity().findViewById(R.id.new_image);++ preview.addListener(new MotionListener() {++ public void onProcess(Bitmap oldBitmap, Bitmap newBitmap,+ boolean motionDetected) {+ oldImage.setImageBitmap(ImageCodec.rotate(oldBitmap,90));+ newImage.setImageBitmap(ImageCodec.rotate(newBitmap,90));++ }+ });++ }++ public void onSensorChanged(SensorEvent event) {++ }+}\ No newline at end of filediff --git a/src/me/ziccard/secureit/fragment/EmptyFragment.java b/src/me/ziccard/secureit/fragment/EmptyFragment.javanew file mode 100644index 0000000..f02ba66--- /dev/null+++ b/src/me/ziccard/secureit/fragment/EmptyFragment.java@@ -0,0 +1,69 @@+package me.ziccard.secureit.fragment;++import me.ziccard.secureit.R;+import android.os.Bundle;+import android.support.v4.app.Fragment;+import android.view.Gravity;+import android.view.LayoutInflater;+import android.view.View;+import android.view.ViewGroup;+import android.widget.RelativeLayout;+import android.widget.TextView;+import android.widget.LinearLayout.LayoutParams;++public final class EmptyFragment extends Fragment {++ private static final String CONTENT = "fragment_content";++ public static EmptyFragment newInstance(String content) {+ EmptyFragment fragment = new EmptyFragment();+++ fragment.mContent = "Service "+content+" disabled";+ return fragment;+ }++ private String mContent = "???";++ @Override+ public void onCreate(Bundle savedInstanceState) {+ super.onCreate(savedInstanceState);+ }++ @Override+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {++ if ((savedInstanceState != null) && savedInstanceState.containsKey(CONTENT)) {+ mContent = savedInstanceState.getString(CONTENT);+ }++ TextView text = new TextView(getActivity());+ text.setGravity(Gravity.CENTER);+ text.setText(mContent);+ text.setTextSize(20 * getResources().getDisplayMetrics().density);++ RelativeLayout layout = new RelativeLayout(getActivity());+ layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));+ layout.setGravity(Gravity.CENTER);++ RelativeLayout alert = new RelativeLayout(getActivity());+ RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);+ params.leftMargin = 20;+ params.rightMargin = 20;+ params.addRule(RelativeLayout.CENTER_HORIZONTAL);+ params.addRule(RelativeLayout.CENTER_IN_PARENT);+ alert.setLayoutParams(params);+ alert.setBackgroundResource(R.drawable.red_back);+ alert.setPadding(30, 0, 30, 0);+ alert.addView(text);+ layout.addView(alert);++ return layout;+ }++ @Override+ public void onSaveInstanceState(Bundle outState) {+ super.onSaveInstanceState(outState);+ outState.putString("CONTENT", mContent);+ }+}\ No newline at end of filediff --git a/src/me/ziccard/secureit/fragment/MicrophoneFragment.java b/src/me/ziccard/secureit/fragment/MicrophoneFragment.javanew file mode 100644index 0000000..d87d5e5--- /dev/null+++ b/src/me/ziccard/secureit/fragment/MicrophoneFragment.java@@ -0,0 +1,147 @@+package me.ziccard.secureit.fragment;++import android.os.Bundle;+import android.graphics.Color;+import android.support.v4.app.Fragment;+import android.util.Log;+import java.text.DecimalFormat;++import me.ziccard.secureit.MicrophoneVolumePicker;+import me.ziccard.secureit.R;+import me.ziccard.secureit.VolumeDynamicSeries;+import me.ziccard.secureit.async.MicSamplerTask;+import com.androidplot.xy.*;+import android.view.LayoutInflater;+import android.view.View;+import android.view.ViewGroup;+import android.widget.LinearLayout;+import android.widget.TextView;+import android.widget.Toast;++public final class MicrophoneFragment extends Fragment implements MicSamplerTask.MicListener{+++ private MicSamplerTask microphone;++ private XYPlot plot;++ private TextView microphoneText;+++ private VolumeDynamicSeries series = new VolumeDynamicSeries(0, "Volume");++ @Override+ public View onCreateView(LayoutInflater inflater, ViewGroup container,+ Bundle savedInstanceState) {+++ return inflater.inflate(R.layout.microphone_fragment, container, false);++ }++ @Override+ public void onCreate(Bundle savedInstanceState) {+ super.onCreate(savedInstanceState);+++ }++ @Override+ public void onPause() {+ super.onPause();+ microphone.terminate();+ }++ @Override+ public void onResume() {+ super.onResume();++ microphoneText = (TextView) getActivity().findViewById(R.id.microphone);++// // initialize our XYPlot reference:+// plot = (XYPlot) getActivity().findViewById(R.id.mySimpleXYPlot);+//+// // Define formatting and add series+// LineAndPointFormatter f1 = new LineAndPointFormatter(Color.rgb(0, 0, 200), null, Color.rgb(0, 0, 80));+// plot.addSeries(series, f1);+//+// // apply some transparency to the series+// f1.getFillPaint().setAlpha(50);+//+// plot.setDomainStepMode(XYStepMode.SUBDIVIDE);+// plot.setDomainStepValue(1);+//+// // thin out domain/range tick labels so they dont overlap each other:+// //plot.setTicksPerDomainLabel(5);+// //plot.setTicksPerRangeLabel(3);+//+// // freeze the range boundaries:+// plot.setRangeBoundaries(0, 120, BoundaryMode.FIXED);+// //plot.setTicksPerRangeLabel(10000);+// //mySimpleXYPlot.setTicksPerDomainLabel(5);+//+// // customize our domain/range labels+// plot.setDomainLabel("");+// plot.setRangeLabel("");+// plot.getLegendWidget().setVisible(false);+//+// // get rid of decimal points in our domain labels:+// plot.setDomainValueFormat(new DecimalFormat("0"));+// //plot.setRangeValueFormat(new DecimalFormat("0"));+//+// // by default, AndroidPlot displays developer guides to aid in laying out your plot.+// // To get rid of them call disableAllMarkup():+// plot.disableAllMarkup();+ LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(+ LinearLayout.LayoutParams.MATCH_PARENT,+ LinearLayout.LayoutParams.WRAP_CONTENT);++ LinearLayout layout = (LinearLayout) getActivity().findViewById(R.id.linear_layout);+ MicrophoneVolumePicker picker = new MicrophoneVolumePicker(this.getActivity());+ layout.addView(picker, params);+++++ microphone = new MicSamplerTask();+ microphone.setMicListener(this);+ microphone.execute();+ }++++ public void onSignalReceived(short[] signal) {++ /*+ * We do and average of the 512 samples+ */+ int total = 0;+ int count = 0;+ for (short peak : signal) {+ Log.i("MicrophoneFragment", "Sampled values are: "+peak);+ if (peak != 0) {+ total+=Math.abs(peak);+ count++;+ }+ }+ Log.i("MicrophoneFragment", "Total value: "+total);+ int average = 0;+ if (count > 0) average = total/count;+ /*+ * We compute a value in decibels+ */+ double averageDB = 0.0;+ if (average!=0) {+ averageDB = 20*Math.log10(Math.abs(average)/1);+ }++ microphoneText.setText("Sampled DBs: "+averageDB);+ }++ public void onMicError() {+ Log.e("MicrophoneActivity", "Microphone is not ready");+ CharSequence text = "Microphone is not ready";+ Toast toast = Toast.makeText(this.getActivity(), text, Toast.LENGTH_LONG);+ toast.show();+ }+}\ No newline at end of filediff --git a/src/me/ziccard/secureit/messages/BluetoothMessage.java b/src/me/ziccard/secureit/messages/BluetoothMessage.javanew file mode 100644index 0000000..ed4152f--- /dev/null+++ b/src/me/ziccard/secureit/messages/BluetoothMessage.java@@ -0,0 +1,9 @@+package me.ziccard.secureit.messages;++import java.io.Serializable;++public interface BluetoothMessage extends Serializable {++ public MessageType getType();++}diff --git a/src/me/ziccard/secureit/messages/BluetoothMessageData.java b/src/me/ziccard/secureit/messages/BluetoothMessageData.javanew file mode 100644index 0000000..c1345aa--- /dev/null+++ b/src/me/ziccard/secureit/messages/BluetoothMessageData.java@@ -0,0 +1,9 @@+package me.ziccard.secureit.messages;++import java.util.Date;++public class BluetoothMessageData {++ protected Date timestamp;++}diff --git a/src/me/ziccard/secureit/messages/HelloMessage.java b/src/me/ziccard/secureit/messages/HelloMessage.javanew file mode 100644index 0000000..79a71c2--- /dev/null+++ b/src/me/ziccard/secureit/messages/HelloMessage.java@@ -0,0 +1,14 @@+package me.ziccard.secureit.messages;++public class HelloMessage extends BluetoothMessageData implements BluetoothMessage {++ /**+ *+ */+ private static final long serialVersionUID = 4363335604763136855L;++ public MessageType getType() {+ return MessageType.HELLO;+ }++}diff --git a/src/me/ziccard/secureit/messages/KeyRequest.java b/src/me/ziccard/secureit/messages/KeyRequest.javanew file mode 100644index 0000000..17dcf2f--- /dev/null+++ b/src/me/ziccard/secureit/messages/KeyRequest.java@@ -0,0 +1,32 @@+package me.ziccard.secureit.messages;++import java.util.Date;++public class KeyRequest extends BluetoothMessageData implements BluetoothMessage {++ private double lat;+ private double lng;++ public KeyRequest(double lat, double lng, Date timestamp) {+ this.lat = lat;+ this.lng = lng;+ this.timestamp = timestamp;+ }++ public double getLat() {+ return lat;+ }++ public double getLng() {+ return lng;+ }+ /**+ *+ */+ private static final long serialVersionUID = -5241265795662117718L;++ public MessageType getType() {+ return MessageType.KEY_REQUEST;+ }++}diff --git a/src/me/ziccard/secureit/messages/KeyResponse.java b/src/me/ziccard/secureit/messages/KeyResponse.javanew file mode 100644index 0000000..9f8a608--- /dev/null+++ b/src/me/ziccard/secureit/messages/KeyResponse.java@@ -0,0 +1,19 @@+package me.ziccard.secureit.messages;++public class KeyResponse extends BluetoothMessageData implements BluetoothMessage {++ /**+ *+ */+ private static final long serialVersionUID = -4625933882220755290L;++ private String accessKey;++ public String getAccessKey() {+ return accessKey;+ }++ public MessageType getType() {+ return MessageType.KEY_RESPONSE;+ }+}diff --git a/src/me/ziccard/secureit/messages/MessageType.java b/src/me/ziccard/secureit/messages/MessageType.javanew file mode 100644index 0000000..230e7cc--- /dev/null+++ b/src/me/ziccard/secureit/messages/MessageType.java@@ -0,0 +1,9 @@+package me.ziccard.secureit.messages;++public enum MessageType {++ HELLO,+ KEY_REQUEST,+ KEY_RESPONSE++}diff --git a/src/me/ziccard/secureit/motiondetection/IMotionDetector.java b/src/me/ziccard/secureit/motiondetection/IMotionDetector.javanew file mode 100644index 0000000..8aec57a--- /dev/null+++ b/src/me/ziccard/secureit/motiondetection/IMotionDetector.java@@ -0,0 +1,19 @@+package me.ziccard.secureit.motiondetection;++import java.util.List;++public interface IMotionDetector {++ /**+ * Detects differences between old and new image+ * and return pixel indexes that differ more than+ * a specified threshold+ * @param oldImage+ * @param newImage+ * @param width+ * @param height+ * @return+ */+ public List<Integer> detectMotion(int[] oldImage, int[] newImage, int width, int height);++}diff --git a/src/me/ziccard/secureit/motiondetection/LuminanceMotionDetector.java b/src/me/ziccard/secureit/motiondetection/LuminanceMotionDetector.javanew file mode 100644index 0000000..aaf40a3--- /dev/null+++ b/src/me/ziccard/secureit/motiondetection/LuminanceMotionDetector.java@@ -0,0 +1,74 @@+package me.ziccard.secureit.motiondetection;++import java.util.ArrayList;+import java.util.List;++import android.graphics.Color;++public class LuminanceMotionDetector implements IMotionDetector {++ /**+ * Difference in lumina for each pixel+ */+ private int VALUE_THRESHOLD = 50;+ /**+ * Difference in number of pixel for each image+ */+ private int NUMBER_THRESHOLD = 10000;++ /**+ *+ */+ private static final int MOTION_LOW = 0;+ private static final int MOTION_MEDIUM = 1;+ private static final int MOTION_HIGH = 2;++ /**+ * Sets different sensitivity for the algorithm+ * @param thresh sensitivity identifier+ */+ public void setThreshold(int thresh) {+ switch(thresh) {+ case MOTION_LOW:+ VALUE_THRESHOLD = 60;+ NUMBER_THRESHOLD = 20000;+ case MOTION_MEDIUM:+ VALUE_THRESHOLD = 50;+ NUMBER_THRESHOLD = 10000;+ case MOTION_HIGH:+ VALUE_THRESHOLD = 40;+ NUMBER_THRESHOLD = 9000;+ }++ }++ /*+ * (non-Javadoc)+ * @see me.ziccard.secureit.motiondetection.IMotionDetector#detectMotion(int[], int[], int, int)+ */+ public List<Integer> detectMotion(int[] oldImage, int[] newImage, int width,+ int height) {+ if (oldImage == null || newImage == null) throw new NullPointerException();+ if (oldImage.length != newImage.length) throw new IllegalArgumentException();++ ArrayList<Integer> differentPixels = new ArrayList<Integer>();+ int differentPixelNumber = 0;+ for (int i = 0, ij=0; i < height; i++) {+ for (int j = 0; j < width; j++, ij++) {+ int newPixelValue = newImage[ij];+ int oldPixelValue = oldImage[ij];+ if (Math.abs(newPixelValue - oldPixelValue) >= VALUE_THRESHOLD) {+ differentPixelNumber++;+ differentPixels.add(ij);++ // sets RED new+ newImage[ij] = Color.RED;+ }+ }+ }+ if (differentPixelNumber > NUMBER_THRESHOLD) return differentPixels;++ return null;+ }++}diff --git a/src/me/ziccard/secureit/opengl/AccelerometerGLRenderer.java b/src/me/ziccard/secureit/opengl/AccelerometerGLRenderer.javanew file mode 100644index 0000000..73204a2--- /dev/null+++ b/src/me/ziccard/secureit/opengl/AccelerometerGLRenderer.java@@ -0,0 +1,617 @@+package me.ziccard.secureit.opengl;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.nio.FloatBuffer;++import javax.microedition.khronos.egl.EGLConfig;+import javax.microedition.khronos.opengles.GL10;++import me.ziccard.secureit.R;++import android.content.Context;+import android.hardware.SensorManager;+import android.opengl.GLES20;+import android.opengl.GLSurfaceView;+import android.opengl.Matrix;+import android.os.SystemClock;+++/**+ * This class implements our custom renderer. Note that the GL10 parameter passed in is unused for OpenGL ES 2.0+ * renderers -- the static class GLES20 is used instead.+ */+public class AccelerometerGLRenderer implements GLSurfaceView.Renderer+{++ /**+ * Angles of the accelerometer+ */+ float angle_x;+ float angle_y;+ float angle_z;+++ float angleToGoX;+ float angleToGoY;+ float angleToGoZ;++ static final float THRESHOLD = 0.1F;++ static final float SMOOTH = 0.1F;++ public void setPosition(float angleX, float angleY, float angleZ) {++ if(Math.abs(angleX-angle_x) > THRESHOLD)+ angleToGoX = angleX;+ if(Math.abs(angleY-angle_y)> THRESHOLD)+ angleToGoY = angleY;+ }++ private final Context mActivityContext;++ /**+ * Store the model matrix. This matrix is used to move models from object space (where each model can be thought+ * of being located at the center of the universe) to world space.+ */+ private float[] mModelMatrix = new float[16];++ /**+ * Store the view matrix. This can be thought of as our camera. This matrix transforms world space to eye space;+ * it positions things relative to our eye.+ */+ private float[] mViewMatrix = new float[16];++ /** Store the projection matrix. This is used to project the scene onto a 2D viewport. */+ private float[] mProjectionMatrix = new float[16];++ /** Allocate storage for the final combined matrix. This will be passed into the shader program. */+ private float[] mMVPMatrix = new float[16];++ /**+ * Stores a copy of the model matrix specifically for the light position.+ */+ private float[] mLightModelMatrix = new float[16];++ /** Store our model data in a float buffer. */+ private final FloatBuffer mCubePositions;+ private final FloatBuffer mCubeColors;+ private final FloatBuffer mCubeNormals;+ private final FloatBuffer mCubeTextureCoordinates;++ /** This will be used to pass in the transformation matrix. */+ private int mMVPMatrixHandle;++ /** This will be used to pass in the modelview matrix. */+ private int mMVMatrixHandle;++ /** This will be used to pass in the light position. */+ private int mLightPosHandle;++ /** This will be used to pass in the texture. */+ private int mTextureUniformHandle;++ /** This will be used to pass in model position information. */+ private int mPositionHandle;++ /** This will be used to pass in model color information. */+ private int mColorHandle;++ /** This will be used to pass in model normal information. */+ private int mNormalHandle;++ /** This will be used to pass in model texture coordinate information. */+ private int mTextureCoordinateHandle;++ /** How many bytes per float. */+ private final int mBytesPerFloat = 4;++ /** Size of the position data in elements. */+ private final int mPositionDataSize = 3;++ /** Size of the color data in elements. */+ private final int mColorDataSize = 4;++ /** Size of the normal data in elements. */+ private final int mNormalDataSize = 3;++ /** Size of the texture coordinate data in elements. */+ private final int mTextureCoordinateDataSize = 2;++ /** Used to hold a light centered on the origin in model space. We need a 4th coordinate so we can get translations to work when+ * we multiply this by our transformation matrices. */+ private final float[] mLightPosInModelSpace = new float[] {0.0f, 0.0f, 0.0f, 1.0f};++ /** Used to hold the current position of the light in world space (after transformation via model matrix). */+ private final float[] mLightPosInWorldSpace = new float[4];++ /** Used to hold the transformed position of the light in eye space (after transformation via modelview matrix) */+ private final float[] mLightPosInEyeSpace = new float[4];++ /** This is a handle to our cube shading program. */+ private int mProgramHandle;++ /** This is a handle to our light point program. */+ private int mPointProgramHandle;++ /** This is a handle to our texture data. */+ private int mTextureDataHandle;++ /**+ * Initialize the model data.+ */+ public AccelerometerGLRenderer(final Context activityContext)+ {+ mActivityContext = activityContext;++ // Define points for a cube.++ // X, Y, Z+ final float[] cubePositionData =+ {+ // In OpenGL counter-clockwise winding is default. This means that when we look at a triangle,+ // if the points are counter-clockwise we are looking at the "front". If not we are looking at+ // the back. OpenGL has an optimization where all back-facing triangles are culled, since they+ // usually represent the backside of an object and aren't visible anyways.++ // Front face+ -1.0f, 1.5f, 1.0f,+ -1.0f, -1.5f, 1.0f,+ 1.0f, 1.5f, 1.0f,+ -1.0f, -1.5f, 1.0f,+ 1.0f, -1.5f, 1.0f,+ 1.0f, 1.5f, 1.0f,++ // Right face+ 1.0f, 1.5f, 1.0f,+ 1.0f, -1.5f, 1.0f,+ 1.0f, 1.5f, 0.9f,+ 1.0f, -1.5f, 1.0f,+ 1.0f, -1.5f, 0.9f,+ 1.0f, 1.5f, 0.9f,++ // Back face+ 1.0f, 1.5f, 0.9f,+ 1.0f, -1.5f, 0.9f,+ -1.0f, 1.5f, 0.9f,+ 1.0f, -1.5f, 0.9f,+ -1.0f, -1.5f, 0.9f,+ -1.0f, 1.5f, 0.9f,++ // Left face+ -1.0f, 1.5f, 0.9f,+ -1.0f, -1.5f, 0.9f,+ -1.0f, 1.5f, 1.0f,+ -1.0f, -1.5f, 0.9f,+ -1.0f, -1.5f, 1.0f,+ -1.0f, 1.5f, 1.0f,++ // Top face+ -1.0f, 1.5f, 0.9f,+ -1.0f, 1.5f, 1.0f,+ 1.0f, 1.5f, 0.9f,+ -1.0f, 1.5f, 1.0f,+ 1.0f, 1.5f, 1.0f,+ 1.0f, 1.5f, 0.9f,++ // Bottom face+ 1.0f, -1.5f, 0.9f,+ 1.0f, -1.5f, 1.0f,+ -1.0f, -1.5f, 0.9f,+ 1.0f, -1.5f, 1.0f,+ -1.0f, -1.5f, 1.0f,+ -1.0f, -1.5f, 0.9f,+ };++ // R, G, B, A+ final float[] cubeColorData =+ {+ // Front face (red)+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,++ // Right face (green)+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,++ // Back face (blue)+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,++ // Left face (yellow)+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,++ // Top face (cyan)+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,++ // Bottom face (magenta)+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f,+ 0.8f, 0.8f, 0.8f, 0.8f+ };++ // X, Y, Z+ // The normal is used in light calculations and is a vector which points+ // orthogonal to the plane of the surface. For a cube model, the normals+ // should be orthogonal to the points of each face.+ final float[] cubeNormalData =+ {+ // Front face+ 0.0f, 0.0f, 1.0f,+ 0.0f, 0.0f, 1.0f,+ 0.0f, 0.0f, 1.0f,+ 0.0f, 0.0f, 1.0f,+ 0.0f, 0.0f, 1.0f,+ 0.0f, 0.0f, 1.0f,++ // Right face+ 1.0f, 0.0f, 0.0f,+ 1.0f, 0.0f, 0.0f,+ 1.0f, 0.0f, 0.0f,+ 1.0f, 0.0f, 0.0f,+ 1.0f, 0.0f, 0.0f,+ 1.0f, 0.0f, 0.0f,++ // Back face+ 0.0f, 0.0f, -1.0f,+ 0.0f, 0.0f, -1.0f,+ 0.0f, 0.0f, -1.0f,+ 0.0f, 0.0f, -1.0f,+ 0.0f, 0.0f, -1.0f,+ 0.0f, 0.0f, -1.0f,++ // Left face+ -1.0f, 0.0f, 0.0f,+ -1.0f, 0.0f, 0.0f,+ -1.0f, 0.0f, 0.0f,+ -1.0f, 0.0f, 0.0f,+ -1.0f, 0.0f, 0.0f,+ -1.0f, 0.0f, 0.0f,++ // Top face+ 0.0f, 1.0f, 0.0f,+ 0.0f, 1.0f, 0.0f,+ 0.0f, 1.0f, 0.0f,+ 0.0f, 1.0f, 0.0f,+ 0.0f, 1.0f, 0.0f,+ 0.0f, 1.0f, 0.0f,++ // Bottom face+ 0.0f, -1.0f, 0.0f,+ 0.0f, -1.0f, 0.0f,+ 0.0f, -1.0f, 0.0f,+ 0.0f, -1.0f, 0.0f,+ 0.0f, -1.0f, 0.0f,+ 0.0f, -1.0f, 0.0f+ };++ // S, T (or X, Y)+ // Texture coordinate data.+ // Because images have a Y axis pointing downward (values increase as you move down the image) while+ // OpenGL has a Y axis pointing upward, we adjust for that here by flipping the Y axis.+ // What's more is that the texture coordinates are the same for every face.+ final float[] cubeTextureCoordinateData =+ {+ // Front face+ 0.0f, 0.0f,+ 0.0f, 1.0f,+ 1.0f, 0.0f,+ 0.0f, 1.0f,+ 1.0f, 1.0f,+ 1.0f, 0.0f,++ // Right face+ 0.0f, 0.0f,+ 0.0f, 1.0f,+ 1.0f, 0.0f,+ 0.0f, 1.0f,+ 1.0f, 1.0f,+ 1.0f, 0.0f,++ // Back face+ 0.0f, 0.0f,+ 0.0f, 1.0f,+ 1.0f, 0.0f,+ 0.0f, 1.0f,+ 1.0f, 1.0f,+ 1.0f, 0.0f,++ // Left face+ 0.0f, 0.0f,+ 0.0f, 1.0f,+ 1.0f, 0.0f,+ 0.0f, 1.0f,+ 1.0f, 1.0f,+ 1.0f, 0.0f,++ // Top face+ 0.0f, 0.0f,+ 0.0f, 1.0f,+ 1.0f, 0.0f,+ 0.0f, 1.0f,+ 1.0f, 1.0f,+ 1.0f, 0.0f,++ // Bottom face+ 0.0f, 0.0f,+ 0.0f, 1.0f,+ 1.0f, 0.0f,+ 0.0f, 1.0f,+ 1.0f, 1.0f,+ 1.0f, 0.0f+ };++ // Initialize the buffers.+ mCubePositions = ByteBuffer.allocateDirect(cubePositionData.length * mBytesPerFloat)+ .order(ByteOrder.nativeOrder()).asFloatBuffer();+ mCubePositions.put(cubePositionData).position(0);++ mCubeColors = ByteBuffer.allocateDirect(cubeColorData.length * mBytesPerFloat)+ .order(ByteOrder.nativeOrder()).asFloatBuffer();+ mCubeColors.put(cubeColorData).position(0);++ mCubeNormals = ByteBuffer.allocateDirect(cubeNormalData.length * mBytesPerFloat)+ .order(ByteOrder.nativeOrder()).asFloatBuffer();+ mCubeNormals.put(cubeNormalData).position(0);++ mCubeTextureCoordinates = ByteBuffer.allocateDirect(cubeTextureCoordinateData.length * mBytesPerFloat)+ .order(ByteOrder.nativeOrder()).asFloatBuffer();+ mCubeTextureCoordinates.put(cubeTextureCoordinateData).position(0);+ }++ protected String getVertexShader()+ {+ return RawResourceReader.readTextFileFromRawResource(mActivityContext, R.raw.per_pixel_vertex_shader);+ }++ protected String getFragmentShader()+ {+ return RawResourceReader.readTextFileFromRawResource(mActivityContext, R.raw.per_pixel_fragment_shader);+ }++ public void onSurfaceCreated(GL10 glUnused, EGLConfig config)+ {+ // Set the background clear color to black.+ GLES20.glClearColor(0.906f, 0.906f, 0.906f, 1.0f);++ // Use culling to remove back faces.+ GLES20.glEnable(GLES20.GL_CULL_FACE);++ // Enable depth testing+ GLES20.glEnable(GLES20.GL_DEPTH_TEST);++ // The below glEnable() call is a holdover from OpenGL ES 1, and is not needed in OpenGL ES 2.+ // Enable texture mapping+ // GLES20.glEnable(GLES20.GL_TEXTURE_2D);++ // Position the eye in front of the origin.+ final float eyeX = 0.0f;+ final float eyeY = 0.0f;+ final float eyeZ = -0.5f;++ // We are looking toward the distance+ final float lookX = 0.0f;+ final float lookY = 0.0f;+ final float lookZ = -5.0f;++ // Set our up vector. This is where our head would be pointing were we holding the camera.+ final float upX = 0.0f;+ final float upY = 1.0f;+ final float upZ = 0.0f;++ // Set the view matrix. This matrix can be said to represent the camera position.+ // NOTE: In OpenGL 1, a ModelView matrix is used, which is a combination of a model and+ // view matrix. In OpenGL 2, we can keep track of these matrices separately if we choose.+ Matrix.setLookAtM(mViewMatrix, 0, eyeX, eyeY, eyeZ, lookX, lookY, lookZ, upX, upY, upZ);++ final String vertexShader = getVertexShader();+ final String fragmentShader = getFragmentShader();++ final int vertexShaderHandle = ShaderHelper.compileShader(GLES20.GL_VERTEX_SHADER, vertexShader);+ final int fragmentShaderHandle = ShaderHelper.compileShader(GLES20.GL_FRAGMENT_SHADER, fragmentShader);++ mProgramHandle = ShaderHelper.createAndLinkProgram(vertexShaderHandle, fragmentShaderHandle,+ new String[] {"a_Position", "a_Color", "a_Normal", "a_TexCoordinate"});++ // Define a simple shader program for our point.+ final String pointVertexShader = RawResourceReader.readTextFileFromRawResource(mActivityContext, R.raw.per_pixel_vertex_shader);+ final String pointFragmentShader = RawResourceReader.readTextFileFromRawResource(mActivityContext, R.raw.per_pixel_fragment_shader);++ final int pointVertexShaderHandle = ShaderHelper.compileShader(GLES20.GL_VERTEX_SHADER, pointVertexShader);+ final int pointFragmentShaderHandle = ShaderHelper.compileShader(GLES20.GL_FRAGMENT_SHADER, pointFragmentShader);+ mPointProgramHandle = ShaderHelper.createAndLinkProgram(pointVertexShaderHandle, pointFragmentShaderHandle,+ new String[] {"a_Position"});++ // Load the texture+ mTextureDataHandle = TextureHelper.loadTexture(mActivityContext, R.drawable.fronttx);+ }++ public void onSurfaceChanged(GL10 glUnused, int width, int height)+ {+ // Set the OpenGL viewport to the same size as the surface.+ GLES20.glViewport(0, 0, width, height);++ // Create a new perspective projection matrix. The height will stay the same+ // while the width will vary as per aspect ratio.+ final float ratio = (float) width / height;+ final float left = -ratio;+ final float right = ratio;+ final float bottom = -1.0f;+ final float top = 1.0f;+ final float near = 1.0f;+ final float far = 10.0f;++ Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);+ }++ public void onDrawFrame(GL10 glUnused)+ {++ GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);++ if(Math.abs(angle_x -angleToGoX) > .4){+ if(angle_x < angleToGoX){+ angle_x += .18;+ }+ else{+ angle_x -= .18;+ }+ }+ if(Math.abs(angle_y -angleToGoY) > .4){+ if(angle_y < angleToGoY){+ angle_y += .18;+ }+ else{+ angle_y -= .18;+ }+ }++ float offsetX = 0.0F;+ float offsetY = 0.0F;+ float angleInDegreesX = (angle_x)/(SensorManager.GRAVITY_EARTH*2)*180;+ float angleInDegreesY = (angle_y)/(SensorManager.GRAVITY_EARTH*2)*180;++ // Set our per-vertex lighting program.+ GLES20.glUseProgram(mProgramHandle);++ // Set program handles for cube drawing.+ mMVPMatrixHandle = GLES20.glGetUniformLocation(mProgramHandle, "u_MVPMatrix");+ mMVMatrixHandle = GLES20.glGetUniformLocation(mProgramHandle, "u_MVMatrix");+ mLightPosHandle = GLES20.glGetUniformLocation(mProgramHandle, "u_LightPos");+ mTextureUniformHandle = GLES20.glGetUniformLocation(mProgramHandle, "u_Texture");+ mPositionHandle = GLES20.glGetAttribLocation(mProgramHandle, "a_Position");+ mColorHandle = GLES20.glGetAttribLocation(mProgramHandle, "a_Color");+ mNormalHandle = GLES20.glGetAttribLocation(mProgramHandle, "a_Normal");+ mTextureCoordinateHandle = GLES20.glGetAttribLocation(mProgramHandle, "a_TexCoordinate");++ // Set the active texture unit to texture unit 0.+ GLES20.glActiveTexture(GLES20.GL_TEXTURE0);++ // Bind the texture to this unit.+ GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextureDataHandle);++ // Tell the texture uniform sampler to use this texture in the shader by binding to texture unit 0.+ GLES20.glUniform1i(mTextureUniformHandle, 0);++ // Calculate position of the light. Rotate and then push into the distance.+ Matrix.setIdentityM(mLightModelMatrix, 0);+ //Ruota il punto di luce su un piano+ //Matrix.rotateM(mLightModelMatrix, 0, angleInDegrees, 0.0f, 1.0f, 0.0f);+ Matrix.translateM(mLightModelMatrix, 0, 0.0f, 0.0f, 2.0f);++ Matrix.multiplyMV(mLightPosInWorldSpace, 0, mLightModelMatrix, 0, mLightPosInModelSpace, 0);+ Matrix.multiplyMV(mLightPosInEyeSpace, 0, mViewMatrix, 0, mLightPosInWorldSpace, 0);++ Matrix.setIdentityM(mModelMatrix, 0);+ Matrix.translateM(mModelMatrix, 0, 0.0f, 0.0f, -4.0f);+ Matrix.rotateM(mModelMatrix, 0, angleInDegreesY, 1.0f, 0.0f, 0.0f);+ Matrix.rotateM(mModelMatrix, 0, angleInDegreesX, 0.0f, 1.0f, 0.0f);+ drawCube();++ // Draw a point to indicate the light.+ GLES20.glUseProgram(mPointProgramHandle);+ drawLight();+ }++ /**+ * Draws a cube.+ */+ private void drawCube()+ {+ // Pass in the position information+ mCubePositions.position(0);+ GLES20.glVertexAttribPointer(mPositionHandle, mPositionDataSize, GLES20.GL_FLOAT, false,+ 0, mCubePositions);++ GLES20.glEnableVertexAttribArray(mPositionHandle);++ // Pass in the color information+ mCubeColors.position(0);+ GLES20.glVertexAttribPointer(mColorHandle, mColorDataSize, GLES20.GL_FLOAT, false,+ 0, mCubeColors);++ GLES20.glEnableVertexAttribArray(mColorHandle);++ // Pass in the normal information+ mCubeNormals.position(0);+ GLES20.glVertexAttribPointer(mNormalHandle, mNormalDataSize, GLES20.GL_FLOAT, false,+ 0, mCubeNormals);++ GLES20.glEnableVertexAttribArray(mNormalHandle);++ // Pass in the texture coordinate information+ mCubeTextureCoordinates.position(0);+ GLES20.glVertexAttribPointer(mTextureCoordinateHandle, mTextureCoordinateDataSize, GLES20.GL_FLOAT, false,+ 0, mCubeTextureCoordinates);++ GLES20.glEnableVertexAttribArray(mTextureCoordinateHandle);++ // This multiplies the view matrix by the model matrix, and stores the result in the MVP matrix+ // (which currently contains model * view).+ Matrix.multiplyMM(mMVPMatrix, 0, mViewMatrix, 0, mModelMatrix, 0);++ // Pass in the modelview matrix.+ GLES20.glUniformMatrix4fv(mMVMatrixHandle, 1, false, mMVPMatrix, 0);++ // This multiplies the modelview matrix by the projection matrix, and stores the result in the MVP matrix+ // (which now contains model * view * projection).+ Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mMVPMatrix, 0);++ // Pass in the combined matrix.+ GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mMVPMatrix, 0);++ // Pass in the light position in eye space.+ GLES20.glUniform3f(mLightPosHandle, mLightPosInEyeSpace[0], mLightPosInEyeSpace[1], mLightPosInEyeSpace[2]);++ // Draw the cube.+ GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 36);+ }++ /**+ * Draws a point representing the position of the light.+ */+ private void drawLight()+ {+ final int pointMVPMatrixHandle = GLES20.glGetUniformLocation(mPointProgramHandle, "u_MVPMatrix");+ final int pointPositionHandle = GLES20.glGetAttribLocation(mPointProgramHandle, "a_Position");++ // Pass in the position.+ GLES20.glVertexAttrib3f(pointPositionHandle, mLightPosInModelSpace[0], mLightPosInModelSpace[1], mLightPosInModelSpace[2]);++ // Since we are not using a buffer object, disable vertex arrays for this attribute.+ GLES20.glDisableVertexAttribArray(pointPositionHandle);++ // Pass in the transformation matrix.+ Matrix.multiplyMM(mMVPMatrix, 0, mViewMatrix, 0, mLightModelMatrix, 0);+ Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mMVPMatrix, 0);+ GLES20.glUniformMatrix4fv(pointMVPMatrixHandle, 1, false, mMVPMatrix, 0);++ // Draw the point.+ // GLES20.glDrawArrays(GLES20.GL_POINTS, 0, 1);+ }+}\ No newline at end of filediff --git a/src/me/ziccard/secureit/opengl/AccelerometerGLSurfaceView.java b/src/me/ziccard/secureit/opengl/AccelerometerGLSurfaceView.javanew file mode 100644index 0000000..6e4ab8a--- /dev/null+++ b/src/me/ziccard/secureit/opengl/AccelerometerGLSurfaceView.java@@ -0,0 +1,21 @@+package me.ziccard.secureit.opengl;++import android.content.Context;+import android.opengl.GLSurfaceView;++public class AccelerometerGLSurfaceView extends GLSurfaceView {++ public AccelerometerGLRenderer renderer;++ public AccelerometerGLSurfaceView(Context context){+ super(context);++ // Create an OpenGL ES 2.0 context+ setEGLContextClientVersion(2);++ renderer = new AccelerometerGLRenderer(context);++ // Set the Renderer for drawing on the GLSurfaceView+ setRenderer(renderer);+ }+}diff --git a/src/me/ziccard/secureit/opengl/RawResourceReader.java b/src/me/ziccard/secureit/opengl/RawResourceReader.javanew file mode 100644index 0000000..7a94ce9--- /dev/null+++ b/src/me/ziccard/secureit/opengl/RawResourceReader.java@@ -0,0 +1,40 @@+package me.ziccard.secureit.opengl;++import java.io.BufferedReader;+import java.io.IOException;+import java.io.InputStream;+import java.io.InputStreamReader;++import android.content.Context;++public class RawResourceReader+{+ public static String readTextFileFromRawResource(final Context context,+ final int resourceId)+ {+ final InputStream inputStream = context.getResources().openRawResource(+ resourceId);+ final InputStreamReader inputStreamReader = new InputStreamReader(+ inputStream);+ final BufferedReader bufferedReader = new BufferedReader(+ inputStreamReader);++ String nextLine;+ final StringBuilder body = new StringBuilder();++ try+ {+ while ((nextLine = bufferedReader.readLine()) != null)+ {+ body.append(nextLine);+ body.append('\n');+ }+ }+ catch (IOException e)+ {+ return null;+ }++ return body.toString();+ }+}diff --git a/src/me/ziccard/secureit/opengl/ShaderHelper.java b/src/me/ziccard/secureit/opengl/ShaderHelper.javanew file mode 100644index 0000000..956725d--- /dev/null+++ b/src/me/ziccard/secureit/opengl/ShaderHelper.java@@ -0,0 +1,103 @@+package me.ziccard.secureit.opengl;++import android.opengl.GLES20;+import android.util.Log;++public class ShaderHelper+{+ private static final String TAG = "ShaderHelper";++ /**+ * Helper function to compile a shader.+ *+ * @param shaderType The shader type.+ * @param shaderSource The shader source code.+ * @return An OpenGL handle to the shader.+ */+ public static int compileShader(final int shaderType, final String shaderSource)+ {+ int shaderHandle = GLES20.glCreateShader(shaderType);++ if (shaderHandle != 0)+ {+ // Pass in the shader source.+ GLES20.glShaderSource(shaderHandle, shaderSource);++ // Compile the shader.+ GLES20.glCompileShader(shaderHandle);++ // Get the compilation status.+ final int[] compileStatus = new int[1];+ GLES20.glGetShaderiv(shaderHandle, GLES20.GL_COMPILE_STATUS, compileStatus, 0);++ // If the compilation failed, delete the shader.+ if (compileStatus[0] == 0)+ {+ Log.e(TAG, "Error compiling shader: " + GLES20.glGetShaderInfoLog(shaderHandle));+ GLES20.glDeleteShader(shaderHandle);+ shaderHandle = 0;+ }+ }++ if (shaderHandle == 0)+ {+ throw new RuntimeException("Error creating shader.");+ }++ return shaderHandle;+ }++ /**+ * Helper function to compile and link a program.+ *+ * @param vertexShaderHandle An OpenGL handle to an already-compiled vertex shader.+ * @param fragmentShaderHandle An OpenGL handle to an already-compiled fragment shader.+ * @param attributes Attributes that need to be bound to the program.+ * @return An OpenGL handle to the program.+ */+ public static int createAndLinkProgram(final int vertexShaderHandle, final int fragmentShaderHandle, final String[] attributes)+ {+ int programHandle = GLES20.glCreateProgram();++ if (programHandle != 0)+ {+ // Bind the vertex shader to the program.+ GLES20.glAttachShader(programHandle, vertexShaderHandle);++ // Bind the fragment shader to the program.+ GLES20.glAttachShader(programHandle, fragmentShaderHandle);++ // Bind attributes+ if (attributes != null)+ {+ final int size = attributes.length;+ for (int i = 0; i < size; i++)+ {+ GLES20.glBindAttribLocation(programHandle, i, attributes[i]);+ }+ }++ // Link the two shaders together into a program.+ GLES20.glLinkProgram(programHandle);++ // Get the link status.+ final int[] linkStatus = new int[1];+ GLES20.glGetProgramiv(programHandle, GLES20.GL_LINK_STATUS, linkStatus, 0);++ // If the link failed, delete the program.+ if (linkStatus[0] == 0)+ {+ Log.e(TAG, "Error compiling program: " + GLES20.glGetProgramInfoLog(programHandle));+ GLES20.glDeleteProgram(programHandle);+ programHandle = 0;+ }+ }++ if (programHandle == 0)+ {+ throw new RuntimeException("Error creating program.");+ }++ return programHandle;+ }+}diff --git a/src/me/ziccard/secureit/opengl/TextureHelper.java b/src/me/ziccard/secureit/opengl/TextureHelper.javanew file mode 100644index 0000000..ad5cce0--- /dev/null+++ b/src/me/ziccard/secureit/opengl/TextureHelper.java@@ -0,0 +1,46 @@+package me.ziccard.secureit.opengl;++import android.content.Context;+import android.graphics.Bitmap;+import android.graphics.BitmapFactory;+import android.opengl.GLES20;+import android.opengl.GLUtils;++public class TextureHelper+{+ public static int loadTexture(final Context context, final int resourceId)+ {+ final int[] textureHandle = new int[1];++ GLES20.glGenTextures(1, textureHandle, 0);++ if (textureHandle[0] != 0)+ {+ final BitmapFactory.Options options = new BitmapFactory.Options();+ options.inScaled = false; // No pre-scaling++ // Read in the resource+ final Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId, options);++ // Bind to the texture in OpenGL+ GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureHandle[0]);++ // Set filtering+ GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);+ GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST);++ // Load the bitmap into the bound texture.+ GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);++ // Recycle the bitmap, since its data has been loaded into OpenGL.+ bitmap.recycle();+ }++ if (textureHandle[0] == 0)+ {+ throw new RuntimeException("Error loading texture.");+ }++ return textureHandle[0];+ }+}diff --git a/src/me/ziccard/secureit/service/BluetoothService.java b/src/me/ziccard/secureit/service/BluetoothService.javanew file mode 100644index 0000000..7652816--- /dev/null+++ b/src/me/ziccard/secureit/service/BluetoothService.java@@ -0,0 +1,314 @@+package me.ziccard.secureit.service;++import java.io.IOException;+import java.io.ObjectInputStream;+import java.io.ObjectOutputStream;+import java.util.ArrayList;+import java.util.Date;++import me.ziccard.secureit.MonitorActivity;+import me.ziccard.secureit.R;+import me.ziccard.secureit.async.BluetoothServerTask;+import me.ziccard.secureit.async.BluetoothServerTask.NoBluetoothException;+import me.ziccard.secureit.bluetooth.ObjectBluetoothSocket;+import me.ziccard.secureit.config.Remote;+import me.ziccard.secureit.messages.BluetoothMessage;+import me.ziccard.secureit.messages.HelloMessage;+import me.ziccard.secureit.messages.KeyRequest;+import me.ziccard.secureit.messages.KeyResponse;+import android.annotation.SuppressLint;+import android.app.Notification;+import android.app.NotificationManager;+import android.app.PendingIntent;+import android.app.Service;+import android.bluetooth.BluetoothAdapter;+import android.bluetooth.BluetoothDevice;+import android.bluetooth.BluetoothSocket;+import android.content.BroadcastReceiver;+import android.content.Context;+import android.content.Intent;+import android.content.IntentFilter;+import android.net.ConnectivityManager;+import android.net.NetworkInfo;+import android.os.Handler;+import android.os.IBinder;+import android.os.Message;+import android.os.Messenger;+import android.util.Log;+import android.widget.Toast;++@SuppressLint("HandlerLeak")+public class BluetoothService extends Service {++ /**+ * To show a notification on service start+ */+ private NotificationManager manager;++ /**+ * Registered clients to the service+ */+ //private ArrayList<Messenger> clients = new ArrayList<Messenger>();++ /**+ * Acceleration detected message+ */+ public static final int ACCELEROMETER_MESSAGE = 0;++ /**+ * Camera motion detected message+ */+ public static final int CAMERA_MESSAGE = 1;++ /**+ * Mic noise detected message+ */+ public static final int MICROPHONE_MESSAGE = 2;++ /**+ * True only if service has been alerted by the accelerometer+ */+ private boolean accelerometer_alerted;++ /**+ * True only if service has been alerted by the camera+ **/+ private boolean camera_alerted;++ /**+ * True only if service has been alerted by the camera+ **/+ private boolean microphone_alerted;++++ /**+ * Adapter for bluetooth services+ */+ private BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();++ /**+ * Handler for incoming messages+ */+ class MessageHandler extends Handler {+ @Override+ public void handleMessage(Message msg) {+ alert(msg.what);+ }+ }++ // Create a BroadcastReceiver for ACTION_FOUND and ACTION_DISCOVERY_FINISHED+ private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {++ private ArrayList<BluetoothDevice> devices = new ArrayList<BluetoothDevice>();++ @Override+ public void onReceive(Context context, Intent intent) {+ String action = intent.getAction();+ // When discovery finds a device+ if (BluetoothDevice.ACTION_FOUND.equals(action)) {+ // Get the BluetoothDevice object from the Intent+ BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);+ devices.add(device);+++ Log.i("BluetoothService", "DISCOVERED "+device.getName());+ CharSequence text = "Discovered "+device.getName();+ int duration = Toast.LENGTH_SHORT;+ Toast toast = Toast.makeText(BluetoothService.this, text, duration);+ toast.show();++ return;+ }+ // When ending the discovery+ if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {+ for (BluetoothDevice device : devices){+ Log.i("DISCOVERY", "FINISHED");+ try {+ BluetoothSocket tmp = null;+ tmp = device.createInsecureRfcommSocketToServiceRecord(Remote.BLUETOOTH_UUID);++ if (tmp != null) {++ Log.i("BluetoothService", "Trying to connect to " + device.getName());++ adapter.cancelDiscovery();+ tmp.connect();++ Log.i("BluetoothService", "Connected to " + device.getName());++ ObjectBluetoothSocket socket = new ObjectBluetoothSocket(tmp);++ //Sending hello message+ BluetoothMessage message = new HelloMessage();+ ObjectOutputStream ostream = socket.getOutputStream();+ message = new HelloMessage();+ ostream.writeObject(message);+ Log.i("BluetoothServerTask", "Sent message " + message.getType().toString());++ //Receiving key request+ ObjectInputStream instream = socket.getInputStream();+ message = (BluetoothMessage) instream.readObject();+ Log.i("BluetoothServerTask", "Received message "+message.getType().toString());++ message = new KeyResponse();+ ostream.writeObject(message);+ Log.i("BluetoothServerTask", "Sent message " + message.getType().toString());++ socket.close();++ CharSequence text = "Written message";+ int duration = Toast.LENGTH_SHORT;+ Toast toast = Toast.makeText(BluetoothService.this, text, duration);+ toast.show();+ }+ } catch (Exception e) {+ e.printStackTrace();+ }+ }+ unregisterReceiver(broadcastReceiver);+ }+ }+ };++ /**+ * Messenger interface used by clients to interact+ */+ private final Messenger messenger = new Messenger(new MessageHandler());++ /**+ * Called on service creation, sends a notification+ */+ @Override+ public void onCreate() {+ manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);++ try {+ new BluetoothServerTask().start();+ } catch (NoBluetoothException e) {+ CharSequence text = "Sorry, bluetooth is off!";+ int duration = Toast.LENGTH_SHORT;+ Toast toast = Toast.makeText(this, text, duration);+ toast.show();+ }++ showNotification();+ }++ /**+ * Called on service destroy, cancels persistent notification+ * and shows a toast+ */+ @Override+ public void onDestroy() {+ // Cancel the persistent notification.+ manager.cancel(R.string.secure_service_started);++ // Tell the user we stopped.+ Toast.makeText(this, R.string.secure_service_stopped, Toast.LENGTH_SHORT).show();+ }++ /**+ * When binding to the service, we return an interface to our messenger+ * for sending messages to the service.+ */+ @Override+ public IBinder onBind(Intent intent) {+ return messenger.getBinder();+ }++ /**+ * Show a notification while this service is running.+ */+ @SuppressWarnings("deprecation")+ private void showNotification() {+ // In this sample, we'll use the same text for the ticker and the expanded notification+ CharSequence text = getText(R.string.secure_service_started);++ Notification notification = new Notification(R.drawable.ic_launcher, text,+ System.currentTimeMillis());++ // The PendingIntent to launch our activity if the user selects this notification+ PendingIntent contentIntent = PendingIntent.getActivity(this, 0,+ new Intent(this, MonitorActivity.class), 0);++ notification.setLatestEventInfo(this, "SecureService",+ text, contentIntent);++ // Send the notification.+ // We use a string id because it is a unique number. We use it later to cancel.+ manager.notify(R.string.secure_service_started, notification);+ }++ /**+ * Sends an alert according to type of connectivity+ */+ private void alert(int alertType) {++ if (accelerometer_alerted && camera_alerted && microphone_alerted) return;++ accelerometer_alerted = true;+ camera_alerted = true;+ microphone_alerted = true;++ /*+ * Need to check the type o connectivity+ */+ ConnectivityManager cm = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);+ NetworkInfo activeNetwork = cm.getActiveNetworkInfo();+ boolean isConnected = activeNetwork.isConnectedOrConnecting();+ boolean isWifi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;+ // Phone is connected+ if (isConnected) {+ // through wireless+ if (isWifi) {+ CharSequence text = "WIFI: we are sending a lot of data";+ int duration = Toast.LENGTH_SHORT;+ Toast toast = Toast.makeText(this, text, duration);+ toast.show();+ //(new DataUploaderTask(null, null, DataUploaderTask.WIFI_CONNECTIVITY)).execute();+ // through 3G+ } else {+ CharSequence text = "3G: we are sending a little of data";+ int duration = Toast.LENGTH_SHORT;+ Toast toast = Toast.makeText(this, text, duration);+ toast.show();+ //(new DataUploaderTask(null, null, DataUploaderTask.3G_CONNECTIVITY)).execute();+ }+ } else {+ CharSequence text = "NO CONNECTIVITY: we are sending an alert";+ int duration = Toast.LENGTH_SHORT;+ Toast toast = Toast.makeText(this, text, duration);+ toast.show();+ //sendBluetoothAlert();+ }+ sendBluetoothAlert();+ }++ /**+ * Discovers clients and sends help alerts+ */+ private void sendBluetoothAlert() {++ registerReceiver(broadcastReceiver,+ new IntentFilter(BluetoothDevice.ACTION_FOUND));++ registerReceiver(broadcastReceiver,+ new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));++ Log.i("BluetoothService", "Started discovery");++ Boolean runningBluetooth = adapter.startDiscovery();++ if (!runningBluetooth) {+ unregisterReceiver(broadcastReceiver);+ CharSequence text = "Sorry, bluetooth is off!";+ int duration = Toast.LENGTH_SHORT;+ Toast toast = Toast.makeText(this, text, duration);+ toast.show();+ }+ }++++}