├── AndroidApp
├── .classpath
├── .gitignore
├── .project
├── .settings
│ └── org.eclipse.jdt.core.prefs
├── AndroidManifest.xml
├── ant.properties
├── build.xml
├── ic_launcher-web.png
├── libs
│ ├── android-support-v4.jar
│ ├── gson-2.3.jar
│ ├── okhttp-2.0.0.jar
│ └── okio-1.0.1.jar
├── proguard-project.txt
├── project.properties
├── res
│ ├── drawable-hdpi
│ │ └── ic_launcher.png
│ ├── drawable-mdpi
│ │ └── ic_launcher.png
│ ├── drawable-xhdpi
│ │ └── ic_launcher.png
│ ├── drawable-xxhdpi
│ │ └── ic_launcher.png
│ ├── layout
│ │ ├── activity_main.xml
│ │ └── list_item_wifi.xml
│ ├── values-v14
│ │ └── styles.xml
│ └── values
│ │ ├── location_names.xml
│ │ ├── strings.xml
│ │ ├── styles.xml
│ │ └── urls.xml
└── src
│ └── com
│ └── zackaryscholl
│ └── wifilocation
│ └── scanner
│ ├── ScanActivity.java
│ ├── UploadService.java
│ ├── ViewResultsActivity.java
│ ├── WifiPoint.java
│ └── WifiScanApplication.java
├── LICENSE
├── README.md
└── RaspberryPi
├── calculatePriors.py
├── databasecommands.py
├── db
└── data.db
├── dbsetup.py
├── index.html
├── server.py
├── server_com.py
└── update.php
/AndroidApp/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/AndroidApp/.gitignore:
--------------------------------------------------------------------------------
1 | *.class
2 | bin
3 | gen
4 | *.jar.properties
5 | local.properties
6 |
--------------------------------------------------------------------------------
/AndroidApp/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | WifiLocationAndroid
4 |
5 |
6 |
7 |
8 |
9 | com.android.ide.eclipse.adt.ResourceManagerBuilder
10 |
11 |
12 |
13 |
14 | com.android.ide.eclipse.adt.PreCompilerBuilder
15 |
16 |
17 |
18 |
19 | org.eclipse.jdt.core.javabuilder
20 |
21 |
22 |
23 |
24 | com.android.ide.eclipse.adt.ApkBuilder
25 |
26 |
27 |
28 |
29 |
30 | com.android.ide.eclipse.adt.AndroidNature
31 | org.eclipse.jdt.core.javanature
32 |
33 |
34 |
--------------------------------------------------------------------------------
/AndroidApp/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
5 | org.eclipse.jdt.core.compiler.compliance=1.7
6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
11 | org.eclipse.jdt.core.compiler.source=1.7
12 |
--------------------------------------------------------------------------------
/AndroidApp/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
10 |
11 |
12 |
13 |
14 |
15 |
21 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
34 |
35 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/AndroidApp/ant.properties:
--------------------------------------------------------------------------------
1 | application.package=com.zackaryscholl.wifilocation.scanner
2 | java.target=1.7
3 | java.source=1.7
4 |
--------------------------------------------------------------------------------
/AndroidApp/build.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
9 |
29 |
30 |
31 |
35 |
36 |
37 |
38 |
39 |
40 |
49 |
50 |
51 |
52 |
56 |
57 |
69 |
70 |
71 |
89 |
90 |
91 |
92 |
93 |
--------------------------------------------------------------------------------
/AndroidApp/ic_launcher-web.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jschools/wifi_triangulation/760d1bea776394c362cb437f4a5b32d47f383365/AndroidApp/ic_launcher-web.png
--------------------------------------------------------------------------------
/AndroidApp/libs/android-support-v4.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jschools/wifi_triangulation/760d1bea776394c362cb437f4a5b32d47f383365/AndroidApp/libs/android-support-v4.jar
--------------------------------------------------------------------------------
/AndroidApp/libs/gson-2.3.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jschools/wifi_triangulation/760d1bea776394c362cb437f4a5b32d47f383365/AndroidApp/libs/gson-2.3.jar
--------------------------------------------------------------------------------
/AndroidApp/libs/okhttp-2.0.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jschools/wifi_triangulation/760d1bea776394c362cb437f4a5b32d47f383365/AndroidApp/libs/okhttp-2.0.0.jar
--------------------------------------------------------------------------------
/AndroidApp/libs/okio-1.0.1.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jschools/wifi_triangulation/760d1bea776394c362cb437f4a5b32d47f383365/AndroidApp/libs/okio-1.0.1.jar
--------------------------------------------------------------------------------
/AndroidApp/proguard-project.txt:
--------------------------------------------------------------------------------
1 | # To enable ProGuard in your project, edit project.properties
2 | # to define the proguard.config property as described in that file.
3 | #
4 | # Add project specific ProGuard rules here.
5 | # By default, the flags in this file are appended to flags specified
6 | # in ${sdk.dir}/tools/proguard/proguard-android.txt
7 | # You can edit the include path and order by changing the ProGuard
8 | # include property in project.properties.
9 | #
10 | # For more details, see
11 | # http://developer.android.com/guide/developing/tools/proguard.html
12 |
13 | # Add any project specific keep options here:
14 |
15 | # If your project uses WebView with JS, uncomment the following
16 | # and specify the fully qualified class name to the JavaScript interface
17 | # class:
18 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
19 | # public *;
20 | #}
21 |
--------------------------------------------------------------------------------
/AndroidApp/project.properties:
--------------------------------------------------------------------------------
1 | # This file is automatically generated by Android Tools.
2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED!
3 | #
4 | # This file must be checked in Version Control Systems.
5 | #
6 | # To customize properties used by the Ant build system edit
7 | # "ant.properties", and override values to adapt the script to your
8 | # project structure.
9 | #
10 | # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
11 | #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
12 |
13 | # Project target.
14 | target=android-20
15 |
--------------------------------------------------------------------------------
/AndroidApp/res/drawable-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jschools/wifi_triangulation/760d1bea776394c362cb437f4a5b32d47f383365/AndroidApp/res/drawable-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/AndroidApp/res/drawable-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jschools/wifi_triangulation/760d1bea776394c362cb437f4a5b32d47f383365/AndroidApp/res/drawable-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/AndroidApp/res/drawable-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jschools/wifi_triangulation/760d1bea776394c362cb437f4a5b32d47f383365/AndroidApp/res/drawable-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/AndroidApp/res/drawable-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jschools/wifi_triangulation/760d1bea776394c362cb437f4a5b32d47f383365/AndroidApp/res/drawable-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/AndroidApp/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
12 |
13 |
20 |
21 |
26 |
27 |
32 |
33 |
38 |
39 |
48 |
49 |
54 |
55 |
60 |
61 |
70 |
71 |
72 |
--------------------------------------------------------------------------------
/AndroidApp/res/layout/list_item_wifi.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
16 |
17 |
23 |
24 |
31 |
32 |
39 |
40 |
--------------------------------------------------------------------------------
/AndroidApp/res/values-v14/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
8 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/AndroidApp/res/values/location_names.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
8 |
9 | Room 0
10 | Room 1
11 | Room 2
12 | Room 3
13 | Room 4
14 | Room 5
15 |
16 |
17 |
--------------------------------------------------------------------------------
/AndroidApp/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | WiFi Scanner
4 | %1$,d data points collected
5 |
6 |
7 |
--------------------------------------------------------------------------------
/AndroidApp/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
14 |
15 |
16 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/AndroidApp/res/values/urls.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | http://morning-wave-7971.herokuapp.com/
6 |
7 |
--------------------------------------------------------------------------------
/AndroidApp/src/com/zackaryscholl/wifilocation/scanner/ScanActivity.java:
--------------------------------------------------------------------------------
1 | package com.zackaryscholl.wifilocation.scanner;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import android.app.Activity;
7 | import android.content.BroadcastReceiver;
8 | import android.content.Context;
9 | import android.content.Intent;
10 | import android.content.IntentFilter;
11 | import android.net.wifi.ScanResult;
12 | import android.net.wifi.WifiManager;
13 | import android.os.Bundle;
14 | import android.os.Handler;
15 | import android.support.v4.content.LocalBroadcastManager;
16 | import android.view.View;
17 | import android.view.View.OnClickListener;
18 | import android.view.Window;
19 | import android.widget.AdapterView;
20 | import android.widget.AdapterView.OnItemSelectedListener;
21 | import android.widget.Spinner;
22 | import android.widget.TextView;
23 | import android.widget.Toast;
24 |
25 | public class ScanActivity extends Activity implements OnClickListener, OnItemSelectedListener {
26 |
27 | private static final String KEY_POINTS = "points";
28 | private static final String KEY_LOCATION = "location";
29 |
30 | private static final int SOFT_UPLOAD_LIMIT_KB = 2 * 1024; // cap out around 2MB
31 | private static final int APPROX_MEASUREMENT_SIZE_B = 90;
32 | private static final int SOFT_COUNT_LIMIT = (SOFT_UPLOAD_LIMIT_KB * 1024) / APPROX_MEASUREMENT_SIZE_B;
33 |
34 | private boolean mScanning;
35 | private boolean mUploading;
36 |
37 | private int mLocation;
38 |
39 | private Handler mHandler;
40 | private ArrayList mPoints;
41 | private final CountAnimator mCountAnimator = new CountAnimator();
42 |
43 | private static final IntentFilter WIFI_FILTER = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
44 | private static final IntentFilter UPLOAD_FILTER = new IntentFilter(UploadService.ACTION_UPLOAD_COMPLETE);
45 | private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
46 | @Override
47 | public void onReceive(Context context, Intent intent) {
48 | switch (intent.getAction()) {
49 | case WifiManager.SCAN_RESULTS_AVAILABLE_ACTION:
50 | appendScanResults();
51 | break;
52 | case UploadService.ACTION_UPLOAD_COMPLETE:
53 | int count = intent.getIntExtra(UploadService.EXTRA_NUM_POINTS, -1);
54 | Toast.makeText(ScanActivity.this, "Server processed " + count + " points", Toast.LENGTH_SHORT).show();
55 | mUploading = false;
56 | updateUiState();
57 | break;
58 | default:
59 | break;
60 | }
61 | }
62 | };
63 |
64 | @Override
65 | protected void onSaveInstanceState(Bundle outState) {
66 | outState.putParcelableArrayList(KEY_POINTS, mPoints);
67 | outState.putInt(KEY_LOCATION, mLocation);
68 | }
69 |
70 | @Override
71 | protected void onCreate(Bundle savedInstanceState) {
72 | super.onCreate(savedInstanceState);
73 |
74 | requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
75 | setContentView(R.layout.activity_main);
76 |
77 | setProgressBarIndeterminate(true);
78 | setProgressBarIndeterminateVisibility(false);
79 |
80 | if (savedInstanceState != null) {
81 | mPoints = savedInstanceState.getParcelableArrayList(KEY_POINTS);
82 | mLocation = savedInstanceState.getInt(KEY_LOCATION, 0);
83 | }
84 |
85 | if (mPoints == null) {
86 | mPoints = new ArrayList();
87 | }
88 | mCountAnimator.setDisplayedCount(mPoints.size());
89 |
90 | mHandler = new Handler();
91 |
92 | Spinner locationSpinner = (Spinner) findViewById(R.id.spinner_location);
93 | locationSpinner.setSelection(Math.min(mLocation, locationSpinner.getCount()));
94 | locationSpinner.setOnItemSelectedListener(this);
95 |
96 | findViewById(R.id.btn_start).setOnClickListener(this);
97 | findViewById(R.id.btn_stop).setOnClickListener(this);
98 | findViewById(R.id.btn_upload).setOnClickListener(this);
99 | findViewById(R.id.btn_clear).setOnClickListener(this);
100 | findViewById(R.id.btn_view).setOnClickListener(this);
101 |
102 | mScanning = false;
103 | mUploading = false;
104 | }
105 |
106 | @Override
107 | protected void onResume() {
108 | super.onResume();
109 |
110 | updateUiState();
111 |
112 | registerReceiver(mReceiver, WIFI_FILTER);
113 | LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(mReceiver, UPLOAD_FILTER);
114 | }
115 |
116 | @Override
117 | protected void onPause() {
118 | super.onPause();
119 |
120 | stopScanning();
121 | mHandler.removeCallbacksAndMessages(null);
122 |
123 | unregisterReceiver(mReceiver);
124 | LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(mReceiver);
125 | }
126 |
127 | @Override
128 | public void onClick(View v) {
129 | switch (v.getId()) {
130 | case R.id.btn_start:
131 | startScanning();
132 | break;
133 | case R.id.btn_stop:
134 | stopScanning();
135 | break;
136 | case R.id.btn_upload:
137 | uploadResults();
138 | break;
139 | case R.id.btn_clear:
140 | clearResults();
141 | break;
142 | case R.id.btn_view:
143 | viewResults();
144 | break;
145 | default:
146 | break;
147 | }
148 | }
149 |
150 | @Override
151 | public void onItemSelected(AdapterView> parent, View view, int position, long id) {
152 | mLocation = position;
153 | }
154 |
155 | @Override
156 | public void onNothingSelected(AdapterView> parent) {
157 | // don't care
158 | }
159 |
160 | private void startScanning() {
161 | mScanning = true;
162 | mHandler.post(mScanRunnable);
163 |
164 | updateUiState();
165 | }
166 |
167 | private void stopScanning() {
168 | mScanning = false;
169 | mHandler.removeCallbacks(mScanRunnable);
170 |
171 | updateUiState();
172 | }
173 |
174 | private void clearResults() {
175 | stopScanning();
176 | mPoints.clear();
177 |
178 | updateUiState();
179 | }
180 |
181 | private void uploadResults() {
182 | stopScanning();
183 |
184 | UploadService.startUpload(new ArrayList<>(mPoints));
185 | mUploading = true;
186 | TextView uploadedCountView = (TextView) findViewById(R.id.uploaded_count);
187 | String message = "Uploading " + mPoints.size() + " data points...";
188 | uploadedCountView.setText(message);
189 |
190 | clearResults();
191 |
192 | updateUiState();
193 | }
194 |
195 | private void viewResults() {
196 | Intent intent = new Intent(this, ViewResultsActivity.class);
197 | intent.putExtra(ViewResultsActivity.EXTA_POINTS, mPoints);
198 | startActivity(intent);
199 | }
200 |
201 | private void updateUiState() {
202 | setProgressBarIndeterminateVisibility(mScanning || mUploading);
203 | findViewById(R.id.spinner_location).setEnabled(!mScanning);
204 | findViewById(R.id.btn_start).setEnabled(!mScanning && !mUploading);
205 | findViewById(R.id.btn_stop).setEnabled(mScanning);
206 | findViewById(R.id.btn_upload).setEnabled(!mScanning && !mUploading && !mPoints.isEmpty());
207 | findViewById(R.id.btn_clear).setEnabled(!mScanning && !mUploading && !mPoints.isEmpty());
208 | findViewById(R.id.uploaded_count).setVisibility(mUploading ? View.VISIBLE : View.GONE);
209 | findViewById(R.id.btn_view).setEnabled(!mScanning && !mUploading && !mPoints.isEmpty());
210 | startAnimatedProgressUpdate();
211 | }
212 |
213 | private void appendScanResults() {
214 | if (!mScanning) {
215 | return;
216 | }
217 |
218 | WifiManager mgr = (WifiManager) getSystemService(WIFI_SERVICE);
219 | List results = mgr.getScanResults();
220 |
221 | long time = System.currentTimeMillis() / 1000;
222 | for (ScanResult scanResult : results) {
223 | mPoints.add(new WifiPoint(scanResult, mLocation, time));
224 | }
225 |
226 | if (mPoints.size() > SOFT_COUNT_LIMIT) {
227 | Toast.makeText(this, "Upload size of " + SOFT_UPLOAD_LIMIT_KB + "kB reached", Toast.LENGTH_SHORT).show();
228 | stopScanning();
229 | }
230 |
231 | startAnimatedProgressUpdate();
232 | }
233 |
234 | private void startAnimatedProgressUpdate() {
235 | mCountAnimator.run();
236 | }
237 |
238 | private class CountAnimator implements Runnable {
239 | private int mDisplayedCount = 0;
240 |
241 | public void setDisplayedCount(int displayedCount) {
242 | mDisplayedCount = displayedCount;
243 | updateProgress(mDisplayedCount);
244 | }
245 |
246 | @Override
247 | public void run() {
248 | mHandler.removeCallbacks(this);
249 |
250 | updateProgress(mDisplayedCount);
251 | final int mPointCount = mPoints.size();
252 | if (mDisplayedCount != mPointCount) {
253 | if (mDisplayedCount < mPoints.size()) {
254 | mDisplayedCount++;
255 | }
256 | else {
257 | mDisplayedCount = Math.max(mPointCount, mDisplayedCount / 2);
258 | }
259 | mHandler.postDelayed(this, 30);
260 | }
261 | }
262 |
263 | private void updateProgress(int dataPointCount) {
264 | String text = getString(R.string.fmt_data_points_collected, Integer.valueOf(dataPointCount));
265 | ((TextView) findViewById(R.id.collected_count)).setText(text);
266 | }
267 | }
268 |
269 | private final Runnable mScanRunnable = new Runnable() {
270 | @Override
271 | public void run() {
272 | mHandler.removeCallbacks(this);
273 |
274 | WifiManager mgr = (WifiManager) getSystemService(WIFI_SERVICE);
275 | boolean started = mgr.startScan();
276 |
277 | if (!started) {
278 | Toast.makeText(ScanActivity.this, "WiFi scan failed to start", Toast.LENGTH_SHORT).show();
279 | stopScanning();
280 | }
281 | else {
282 | mHandler.postDelayed(this, 500);
283 | }
284 | }
285 | };
286 |
287 | }
288 |
--------------------------------------------------------------------------------
/AndroidApp/src/com/zackaryscholl/wifilocation/scanner/UploadService.java:
--------------------------------------------------------------------------------
1 | package com.zackaryscholl.wifilocation.scanner;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import android.app.IntentService;
7 | import android.content.Context;
8 | import android.content.Intent;
9 | import android.support.v4.content.LocalBroadcastManager;
10 |
11 | import com.google.gson.Gson;
12 | import com.squareup.okhttp.MediaType;
13 | import com.squareup.okhttp.OkHttpClient;
14 | import com.squareup.okhttp.Request;
15 | import com.squareup.okhttp.RequestBody;
16 | import com.squareup.okhttp.Response;
17 |
18 | public class UploadService extends IntentService {
19 |
20 | public static final String SERVICE_NAME = UploadService.class.getSimpleName();
21 |
22 | private static final String ACTION_UPLOAD = "UploadService.ACTION_UPLOAD";
23 | private static final String EXTRA_POINTS = "points";
24 | public static final String ACTION_UPLOAD_COMPLETE = "UploadService.ACTION_UPLOAD_COMPLETE";
25 | public static final String EXTRA_NUM_POINTS = "numPoints";
26 |
27 | public static void startUpload(List points) {
28 | Context context = WifiScanApplication.getInstance();
29 |
30 | Intent intent = new Intent(context, UploadService.class);
31 | intent.setAction(ACTION_UPLOAD);
32 |
33 | ArrayList arrayList;
34 | if (points instanceof ArrayList) {
35 | arrayList = (ArrayList) points;
36 | }
37 | else {
38 | arrayList = new ArrayList<>(points);
39 | }
40 | intent.putParcelableArrayListExtra(EXTRA_POINTS, arrayList);
41 |
42 | context.startService(intent);
43 | }
44 |
45 | public UploadService() {
46 | super(SERVICE_NAME);
47 | }
48 |
49 | @Override
50 | protected void onHandleIntent(Intent intent) {
51 | switch (intent.getAction()) {
52 | case ACTION_UPLOAD:
53 | handleUpload(intent);
54 | break;
55 | default:
56 | break;
57 | }
58 | }
59 |
60 | private void handleUpload(Intent intent) {
61 | final String url = getString(R.string.url_upload);
62 | final List points = intent.getParcelableArrayListExtra(EXTRA_POINTS);
63 | final String json = new Gson().toJson(points);
64 |
65 | RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
66 |
67 | Request.Builder builder = new Request.Builder();
68 | builder.url(url).post(body);
69 | Request request = builder.build();
70 |
71 | OkHttpClient client = new OkHttpClient();
72 | try {
73 | Response response = client.newCall(request).execute();
74 | final int code = response.code();
75 | if (code == 200) {
76 | final String responseBody = response.body().string();
77 | int count = Integer.parseInt(responseBody);
78 | broadcastCompletion(count);
79 | return;
80 | }
81 | }
82 | catch (Exception e) {
83 | e.printStackTrace();
84 | }
85 |
86 | broadcastCompletion(-1);
87 | }
88 |
89 | private static void broadcastCompletion(int count) {
90 | Intent intent = new Intent(ACTION_UPLOAD_COMPLETE);
91 | intent.putExtra(EXTRA_NUM_POINTS, count);
92 | LocalBroadcastManager.getInstance(WifiScanApplication.getInstance()).sendBroadcast(intent);
93 | }
94 |
95 | }
96 |
--------------------------------------------------------------------------------
/AndroidApp/src/com/zackaryscholl/wifilocation/scanner/ViewResultsActivity.java:
--------------------------------------------------------------------------------
1 | package com.zackaryscholl.wifilocation.scanner;
2 |
3 | import java.util.List;
4 |
5 | import android.app.ListActivity;
6 | import android.content.Context;
7 | import android.os.Bundle;
8 | import android.view.LayoutInflater;
9 | import android.view.View;
10 | import android.view.ViewGroup;
11 | import android.widget.ArrayAdapter;
12 | import android.widget.TextView;
13 |
14 | public class ViewResultsActivity extends ListActivity {
15 |
16 | public static final String EXTA_POINTS = ViewResultsActivity.class.getName() + ".EXTRA_POINTS";
17 |
18 | private List mPoints;
19 |
20 | @Override
21 | protected void onCreate(Bundle savedInstanceState) {
22 | super.onCreate(savedInstanceState);
23 |
24 | mPoints = getIntent().getParcelableArrayListExtra(EXTA_POINTS);
25 | setListAdapter(new WifiPointAdapter(this, mPoints));
26 | }
27 |
28 | private static class WifiPointAdapter extends ArrayAdapter {
29 |
30 | public WifiPointAdapter(Context context, List objects) {
31 | super(context, R.layout.list_item_wifi, objects);
32 | }
33 |
34 | @Override
35 | public View getView(int position, View convertView, ViewGroup parent) {
36 | View v = convertView;
37 | ViewHolder holder;
38 | if (v == null) {
39 | v = LayoutInflater.from(getContext()).inflate(R.layout.list_item_wifi, parent, false);
40 | holder = new ViewHolder(v);
41 | v.setTag(holder);
42 | }
43 | else {
44 | holder = (ViewHolder) v.getTag();
45 | }
46 |
47 | final WifiPoint point = getItem(position);
48 | holder.position.setText(Integer.toString(position));
49 | holder.mac.setText("MAC: " + point.macAddress);
50 | holder.rssi.setText("RSSI: " + point.rssi);
51 | holder.location.setText("Location: " + point.location);
52 |
53 | return v;
54 | }
55 |
56 | private static class ViewHolder {
57 | public final TextView position;
58 | public final TextView mac;
59 | public final TextView rssi;
60 | public final TextView location;
61 |
62 | public ViewHolder(View v) {
63 | position = (TextView) v.findViewById(R.id.position);
64 | mac = (TextView) v.findViewById(R.id.mac);
65 | rssi = (TextView) v.findViewById(R.id.rssi);
66 | location = (TextView) v.findViewById(R.id.location);
67 | }
68 | }
69 |
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/AndroidApp/src/com/zackaryscholl/wifilocation/scanner/WifiPoint.java:
--------------------------------------------------------------------------------
1 | package com.zackaryscholl.wifilocation.scanner;
2 |
3 | import android.net.wifi.ScanResult;
4 | import android.os.Parcel;
5 | import android.os.Parcelable;
6 |
7 | import com.google.gson.annotations.SerializedName;
8 |
9 | public class WifiPoint implements Parcelable {
10 |
11 | @SerializedName("mac")
12 | public final String macAddress;
13 |
14 | @SerializedName("rssi")
15 | public final int rssi;
16 |
17 | @SerializedName("room")
18 | public final int location;
19 |
20 | @SerializedName("time")
21 | public final long timestamp;
22 |
23 | public WifiPoint(ScanResult scanResult, int location, long time) {
24 | macAddress = scanResult.BSSID;
25 | rssi = scanResult.level;
26 | this.location = location;
27 | timestamp = time;
28 | }
29 |
30 | @Override
31 | public int describeContents() {
32 | return 0;
33 | }
34 |
35 | @Override
36 | public void writeToParcel(Parcel dest, int flags) {
37 | dest.writeString(macAddress);
38 | dest.writeInt(rssi);
39 | dest.writeInt(location);
40 | dest.writeLong(timestamp);
41 | }
42 |
43 | private WifiPoint(Parcel in) {
44 | macAddress = in.readString();
45 | rssi = in.readInt();
46 | location = in.readInt();
47 | timestamp = in.readLong();
48 | }
49 |
50 | public static final Creator CREATOR = new Creator() {
51 | @Override
52 | public WifiPoint createFromParcel(Parcel source) {
53 | return new WifiPoint(source);
54 | }
55 |
56 | @Override
57 | public WifiPoint[] newArray(int size) {
58 | return new WifiPoint[size];
59 | }
60 |
61 | };
62 |
63 | }
64 |
--------------------------------------------------------------------------------
/AndroidApp/src/com/zackaryscholl/wifilocation/scanner/WifiScanApplication.java:
--------------------------------------------------------------------------------
1 | package com.zackaryscholl.wifilocation.scanner;
2 |
3 | import android.app.Application;
4 |
5 | public class WifiScanApplication extends Application {
6 |
7 | private static WifiScanApplication sInstance;
8 |
9 | @Override
10 | public void onCreate() {
11 | super.onCreate();
12 |
13 | sInstance = this;
14 | }
15 |
16 | public static WifiScanApplication getInstance() {
17 | return sInstance;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | {description}
294 | Copyright (C) {year} {fullname}
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | {signature of Ty Coon}, 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | wifi_triangulation
2 | ==================
3 |
4 | Uses Android phone and Raspberry Pi for an adhoc Internal Positioning System with ~10ft resolution
5 |
6 | ###### Please note that this setup as described is supposed to be a proof of principle. It is far from polished. What I attempt here serves as a springboard for further development. My goals here were determine 1) Does WiFi triangulation work at all? 2) What is the best application if Bayes Theorem (prior and posteriors)? 3) What sort of resolution and accuracy can be determined? I think I've answered these questions as you read.
7 |
8 | # Requirements
9 |
10 | - ~~Matlab with [mqsqlite](http://sourceforge.net/projects/mksqlite/)~~ (08/30/14: Python does all this now!)
11 | - Python+SQLite (I hope to remove this dependency eventually)
12 | - Android SDK
13 | - ~~[Tasker for Android](http://tasker.dinglisch.net/)~~ (08/30/14: Android App can do this now!)
14 |
15 |
16 | # Future development
17 |
18 | - ~~Use Python instead of Matlab to determine the fixed Posterior distributions and off load almost everything to the Raspberry Pi~~ **Made possible using simpler (and just as effective) prior calculation scheme**
19 | - ~~Make the Android app more friendly and not reliant on Tasker~~ **Thank you [jschools](https://github.com/jschools)**
20 | - Allow Android to collect data in the background
21 | - Ability to change URL in AndroidApp
22 | - Eventually make entire process self contained in an Android app (Sqlite database, building priors, and posterior calculation)
23 | - Markov model for better location matching
24 |
25 | # Short term to-do
26 |
27 | - Get rid of redundant data (priors of mac addresses)
28 |
29 | # Acknowledgements
30 |
31 | Thanks to Travis provided all the database code for Python and helped me get all of that started. Thanks to [jschools](https://github.com/jschools) got the android app and php uploading working!
32 |
33 |
34 | # Background Information
35 |
36 | ## Implementation
37 |
38 | Basically this relies on you walking to a designated location and waiting for 10minutes while devices collect information about the WiFi networks and strengths at that spot. Once all the locations have been "learned" then it simply calculates the Bayesian probability of location X given a WiFi signal from router Y with signal Z. It does this using Bayes' theorem:
39 |
40 | 
41 |
42 | In this case, since there are Y routers and X locations, we use version of Bayes' theorem with multiple observations:
43 |
44 | 
45 |
48 |
49 | which can be simplifed (for computational reasons) using the Log-likelihood:
50 |
51 | 
52 |
53 |
56 |
57 |
58 | I'll go over how I implemented this code using my apartment as an example
59 |
60 | ## Learning locations
61 |
62 | My apartment is almost exactly 1,000 sq ft. I divided my apartment into 8 frequented locations (shown by yellow circles):
63 |
64 | 
65 |
66 | The first task is to aquire several hundred scans of all the WiFi networks and save them to a database. I have a roundabout way of doing this, hopefully to be improved in the future.
67 |
68 | I've used an SQLite database on the Raspberry Pi to store all the variables ```db/data.db```. The database was created using Python scripts ```dbsetup.py``` written by Travis. Records are inserted one at a time using a PHP script, ```update.php```. This PHP script has three inputs: MAC address, signal strength, location number (0 if not known) which are presented comma-delimited into the loc variable (i.e. ```http://blahblahblah/update.php?loc=3d:ma:c3:ad:d3,-54,1```.
69 |
70 | The WiFi information is gathered from my Android device - a Droid DNA phone. I wrote a *really* simple App (```My First App```) which simply writes to a file all of the MAC addresses and signal strengths, pipe-delimited. I wish I was smart enough to write the app to do this for a few minutes and goto the webaddress above to insert the records, but I'm not. So instead I used [Tasker](Tasker url) which does the following loop: 1) Run my stupid App, 2) Read file with MAC address and signal strength, 3) Open URL to update the Raspbery Pi database with each MAC address in file, 4) Go back to 1) a 100 times. That's it. I just go to every location in my apartment, tell the Tasker handler which room I'm in and let it run for awhile. After doing this for each location, the database is populated and ready for determining Bayesion probabilties
71 |
72 | ### Determining Bayesian probabilities
73 |
74 | These distributions depend on the WiFi strength signals. I initialliy tried using Gaussian mixture models, but found a much simpler and effective way is to just estimate the probabilities by the number of events at a given RSSI divided by the total number of events. This costs more overhead, but its not much more and its insignificant as long as your not polling thousands of locations.
75 |
76 | Example of some distriubtions are here:
77 |
78 | 
79 |
80 | I used small Gaussians to make up the final model which is why it looks smooth. You can see here, even from an example with two locations ~10ft apart (Room 1 and Room 2) there is a substantial difference between the probabilities for a given room AND MAC address (blue and green). The prior for the distribution of the MAC address only (red) is essentially all possible probabilities.
81 |
82 | ### Simulations
83 |
84 | Here are some simulations from real data. This code essential picks a room and then picks random signals from that room and tests how often it is correct. In general, this method is accurate **>95%** of the time. There are some places it does better than others, but good overall:
85 |
86 | 
87 |
88 |
89 | # Step-by-step guide to implementation
90 |
91 | **In progress**
92 |
93 | 0. This project really works well with a Raspbery Pi. Get one and install python and sqlite3. I believe its fine if you use the local network, but make sure to forward Port 9003 so the websockets will work. Put the ```RaspberryPi``` files in your public html folder, ```/var/www/```.
94 |
95 | 1. First run ```dbsetup.py``` to set up the table.
96 |
97 | 2. Use the Android app now, pointing the app towards your URL of ```update.php```. Walk around to each room and collect some data points and upload them to the server. Be sure to register which room your in! This step is worth repeating every once and awhile.
98 |
99 | 3. Once you have data, run ```calculatePriors.py``` which will save a Pickle of the parameters for all the mac addresses and locations in your database. This takes a few minutes so thats why its a separate file.
100 |
101 | 4. To start up the server now, first make sure your IP addresses in ```index.html``` and ```server_com.py``` are correct. Then run ```nohup python server.py &``` to start the main listener and then ```nohup python server_com.py &``` to start the calculation of Bayesian probabilities. It will calculate about once per second. The calculations will automatically update on ```index.html```.
102 |
--------------------------------------------------------------------------------
/RaspberryPi/calculatePriors.py:
--------------------------------------------------------------------------------
1 | import numpy
2 | import cPickle as pickle
3 | import math
4 | from sqlite3 import connect
5 |
6 | conn = connect('/var/www/where3/db/data.db') # use your own location here
7 |
8 | # Determine all unique rooms and mac addressed automatically
9 | c = conn.cursor()
10 | macs = []
11 | for row in c.execute("select distinct mac from locations where room>0"):
12 | macs.append(str(row[0]).decode('utf-8'))
13 |
14 | rooms = []
15 | for row in c.execute("select distinct room from locations where room>0"):
16 | rooms.append(str(row[0]).decode('utf-8'))
17 |
18 | # Initialize probabilities
19 | P={}
20 | nP={}
21 | Wdefault = {}
22 | for mac in macs:
23 | Wdefault[mac]=0
24 | P[mac]={}
25 | nP[mac]={}
26 | nP[mac] = numpy.zeros(100)
27 | for room in rooms:
28 | P[mac][room] = numpy.zeros(100)
29 |
30 | # Add a Gaussian centered around RSSI with STD of 1 RSSI - this takes awhile
31 | for mac in macs:
32 | for room in rooms:
33 | for row in c.execute("select rssi from (select rssi from locations where mac like '" + mac + "' and room=" + str(room) + ")"):
34 | try:
35 | P[mac][room][row[0]+100]=P[mac][room][row[0]+100]+0.4
36 | P[mac][room][row[0]+99]=P[mac][room][row[0]+99]+0.14
37 | P[mac][room][row[0]+101]=P[mac][room][row[0]+101]+0.14
38 | P[mac][room][row[0]+98]=P[mac][room][row[0]+98]+0.06
39 | P[mac][room][row[0]+102]=P[mac][room][row[0]+102]+0.06
40 | P[mac][room][row[0]+97]=P[mac][room][row[0]+97]+0.06
41 | P[mac][room][row[0]+103]=P[mac][room][row[0]+103]+0.06
42 | except Exception,e:
43 | print str(e)
44 | for row in c.execute("select rssi from locations where mac like '" + mac + "' and room>0"):
45 | try:
46 | nP[mac][row[0]+100]=nP[mac][row[0]+100]+0.4
47 | nP[mac][row[0]+99]=nP[mac][row[0]+99]+0.14
48 | nP[mac][row[0]+101]=nP[mac][row[0]+101]+0.14
49 | nP[mac][row[0]+98]=nP[mac][row[0]+98]+0.06
50 | nP[mac][row[0]+102]=nP[mac][row[0]+102]+0.06
51 | nP[mac][row[0]+97]=nP[mac][row[0]+97]+0.06
52 | nP[mac][row[0]+103]=nP[mac][row[0]+103]+0.06
53 | except Exception,e:
54 | print str(e)
55 |
56 | # close the database
57 | conn.close()
58 |
59 | # Normalize the distributions
60 | for mac in macs:
61 | for room in rooms:
62 | pTotal = sum(P[mac][room])
63 | if pTotal>0:
64 | for i in range(100):
65 | P[mac][room][i] = P[mac][room][i]/pTotal
66 | npTotal = sum(nP[mac])
67 | if npTotal>0:
68 | for i in range(100):
69 | nP[mac][i] = nP[mac][i]/npTotal
70 |
71 | # Dumpe them to a pickle
72 | data = pickle.dumps(P,2)
73 | pickle.dump(data,open('P.p','wb'))
74 | data = pickle.dumps(nP,2)
75 | pickle.dump(data,open('nP.p','wb'))
76 | data = pickle.dumps(Wdefault,2)
77 | pickle.dump(data,open('W.p','wb'))
78 |
--------------------------------------------------------------------------------
/RaspberryPi/databasecommands.py:
--------------------------------------------------------------------------------
1 | import sqlite3
2 | import hashlib
3 | import re
4 |
5 | class DataBase:
6 |
7 | def __init__(self,name):
8 | self.name = name
9 | self.conn = sqlite3.connect(self.name)
10 | self.c = self.conn.cursor()
11 |
12 |
13 | def close(self):
14 | self.conn.close()
15 | self.conn = None
16 | self.c = None
17 |
18 |
19 | '''DATA'''
20 |
21 |
22 | def getAllData(self):
23 | return [row for row in self.c.execute('SELECT * FROM locations')]
24 |
25 | #NOT USER INPUT#id: auto generated just add null
26 | #lat: latitude
27 | #long: longitude
28 | #NOT USER INPUT#date: YYYY-MM-DD HH:MM:SS
29 | def addData(self,mac,rssi,room):
30 | self.c.execute('SELECT strftime("%s","now")')
31 | date = self.c.fetchone()[0]
32 | self.c.execute('INSERT INTO locations VALUES (?,?,?,?,?)',(None,mac,rssi,room,date))
33 | id = self.c.lastrowid
34 | #remember to commit changes so we don't lock the db!
35 | self.conn.commit()
36 | return True
37 |
38 | def removeData(self,id):
39 | self.c.execute('DELETE FROM locations WHERE id=?',(id,))
40 | self.conn.commit()
41 |
42 | def getData(self,id):
43 | return [row for row in self.c.execute('SELECT * FROM locations WHERE id=(?)',(id,))]
44 |
45 |
46 | '''
47 |
48 | GENERAL TABLE COMMANDS
49 |
50 | '''
51 |
52 |
53 | #returns true if table exists
54 | def tableExists(self,table_name):
55 | self.c.execute('SELECT count(*) FROM sqlite_master WHERE type="table" AND name=?;',(table_name,))
56 | return not self.c.fetchone()[0] is 0
57 |
58 |
59 | #builds table if doesn't already exist
60 | #-a little sketchy
61 | def createTable(self,table_data):
62 | if self.tableExists(table_data):
63 | return False
64 | else:
65 | self.c.execute('CREATE TABLE %s;' % table_data)
66 | self.conn.commit()
67 | return True
68 |
69 |
70 | #drops table
71 | #-a little sketchy
72 | def dropTable(self,table_name):
73 | if self.tableExists(table_name):
74 | self.c.execute('DROP TABLE %s' % table_name)
75 | self.conn.commit()
76 | return True
77 | else:
78 | return False
79 |
--------------------------------------------------------------------------------
/RaspberryPi/db/data.db:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jschools/wifi_triangulation/760d1bea776394c362cb437f4a5b32d47f383365/RaspberryPi/db/data.db
--------------------------------------------------------------------------------
/RaspberryPi/dbsetup.py:
--------------------------------------------------------------------------------
1 | import sqlite3
2 | import hashlib
3 |
4 | exec(open('databasecommands.py').read())
5 |
6 | DB = DataBase('db/data.db')
7 |
8 | #
9 | #SET UP INITIAL TABLES
10 | #
11 |
12 | #locations TABLE
13 |
14 | if not DB.tableExists('locations'):
15 | print('no table "locations"... making one now...')
16 | #lat: latitude
17 | #long: longitude
18 | #time: unix time stamp, unixepoch
19 | DB.createTable('locations ('\
20 | +'id INTEGER PRIMARY KEY AUTOINCREMENT, '\
21 | +'mac TEXT, '\
22 | +'rssi INTEGER, '\
23 | +'room INTEGER, '\
24 | +'time INTEGER'\
25 | +')')
26 | else:
27 | print('already "locations" table')
28 |
29 | print('adding test data...')
30 | if DB.getData(1):
31 | print('already data..')
32 | else:
33 | DB.addData('none',0,0)
34 |
35 | def _resetDB():
36 | DB.dropTable('locations')
37 | DB.close()
38 |
--------------------------------------------------------------------------------
/RaspberryPi/index.html:
--------------------------------------------------------------------------------
1 |
2 | WiFi IPS
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
--------------------------------------------------------------------------------
/RaspberryPi/server.py:
--------------------------------------------------------------------------------
1 | import tornado.httpserver
2 | import tornado.websocket
3 | import tornado.ioloop
4 | import tornado.web
5 | import time
6 | import socket
7 | import sys
8 |
9 | def get_lock(process_name):
10 | global lock_socket
11 | lock_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
12 | try:
13 | lock_socket.bind('\0' + process_name)
14 | print 'I got the lock'
15 | except socket.error:
16 | print 'lock exists'
17 | sys.exit()
18 |
19 | class WSHandler(tornado.websocket.WebSocketHandler):
20 | clients = []
21 | def open(self):
22 | self.clients.append(self)
23 | print 'New connection was opened'
24 | self.write_message("Con!")
25 |
26 | def on_message(self, message):
27 | #print 'Got :', message
28 | for s in self.clients:
29 | s.write_message(message)
30 |
31 | def on_close(self):
32 | self.clients.remove(self)
33 | print 'Conn closed...'
34 |
35 | application = tornado.web.Application([
36 | (r'/ws', WSHandler),
37 | ])
38 |
39 |
40 | if __name__ == "__main__":
41 | get_lock('server_python')
42 | http_server = tornado.httpserver.HTTPServer(application)
43 | http_server.listen(9003)
44 | tornado.ioloop.IOLoop.instance().start()
45 |
46 |
--------------------------------------------------------------------------------
/RaspberryPi/server_com.py:
--------------------------------------------------------------------------------
1 | import subprocess as s
2 | from websocket import create_connection
3 | import thread
4 | import os
5 | import socket
6 | from sys import exit , stdout , stdin
7 | import serial
8 | import datetime
9 | import socket
10 | import sys
11 | from time import time,strftime,localtime,sleep
12 | from sqlite3 import connect
13 | import cPickle as pickle
14 | import math
15 | from operator import itemgetter
16 | import numpy
17 | from collections import deque
18 |
19 |
20 | base_directory = "/var/www/where3/"
21 | ip_address = '127.0.0.1:9003'
22 |
23 | def get_lock(process_name):
24 | global lock_socket
25 | lock_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
26 | try:
27 | lock_socket.bind('\0' + process_name)
28 | print 'I got the lock'
29 | except socket.error:
30 | print 'lock exists'
31 | sys.exit()
32 |
33 | def getMessages():
34 | while 1:
35 | result = ws.recv()
36 | print result
37 |
38 |
39 | def sendState(msg):
40 | try:
41 | ws.send(msg)
42 | except:
43 | pass
44 |
45 |
46 | get_lock('python_server_com_where3')
47 |
48 | # Load main data
49 | start_time = time()
50 | start_time2 = time()
51 | data=pickle.load(open(base_directory+'P.p','rb'))
52 | P=pickle.loads(data)
53 | data=pickle.load(open(base_directory+'nP.p','rb'))
54 | nP=pickle.loads(data)
55 | data=pickle.load(open(base_directory+'W.p','rb'))
56 | Wdefault=pickle.loads(data)
57 | print "Loaded data (%2.1f seconds) " % (time() - start_time)
58 | start_time=time()
59 | fifo=deque([0,0,0,0,0,0,0,0,0,0,0])
60 |
61 |
62 |
63 | # setup server connections
64 | ws = create_connection("ws://"+ip_address+"/ws")
65 | sendState('hello')
66 | try:
67 | thread.start_new_thread(getMessages,())
68 | except:
69 | sys.exit(0)
70 | lastTime = 0
71 | curTime = 0
72 | while 1:
73 | sleep(1)
74 | conn = connect(base_directory+'db/data.db')
75 | c = conn.cursor()
76 | for row in c.execute("select time from locations order by id desc limit 1"):
77 | curTime = row[0]
78 | conn.close()
79 |
80 | if (curTime==lastTime):
81 | pass
82 | else:
83 |
84 | conn = connect(base_directory+'db/data.db')
85 | c = conn.cursor()
86 | W=Wdefault
87 | #for row in c.execute("SELECT mac,rssi FROM locations WHERE time>STRFTIME('%s',DATETIME('now','-30 hours'))GROUP BY mac"):
88 | #for row in c.execute("select mac,rssi from (select id,mac,rssi from locations order by id desc limit 30) group by mac"):
89 | for row in c.execute("select mac,Avg(rssi) as rssi from (select * from locations order by id desc limit 100) group by mac"):
90 | W[str(row[0]).decode('utf-8')]=row[1]
91 |
92 | conn.close()
93 | print "Pulled database (%2.1f seconds) " % (time() - start_time)
94 | start_time=time()
95 | locations = P[P.keys()[0]].keys()
96 | macs = P.keys()
97 | numberLocations = len(locations)
98 | numberMACs = len(macs)
99 |
100 | P_bayes = {}
101 | for loc in locations:
102 | P_bayes[loc]=0
103 |
104 | P_A = 1.0/numberLocations;
105 | P_notA = (numberLocations-1.0)/numberLocations;
106 | for loc in locations:
107 | P_bayes[loc] = 0
108 | P_B_notA = 0
109 | P_B_A = math.log(P_A)
110 | for mac in macs:
111 | if (W[mac]<0):
112 | pInd = int(W[mac]+100)
113 | pFoo = P[mac][loc][pInd]
114 | if (pFoo > 0):
115 | P_B_A = P_B_A + math.log(pFoo)
116 | pFoo = nP[mac][pInd]
117 | if (pFoo > 0):
118 | P_B_notA = P_B_notA + math.log(pFoo)
119 | P_bayes[loc] = (P_B_A)-(P_B_notA)
120 |
121 | start_time=time()
122 |
123 | sorted_P_bayes = {}
124 | sorted_P_bayes = sorted(P_bayes.iteritems(), key=itemgetter(1),reverse=True)
125 | first = True
126 | toSend = "Log-likelihood: Room\n"
127 | for s in sorted_P_bayes:
128 | if first:
129 | toSend = toSend + "%2.3f: %s\n" % (s[1],s[0])
130 | first = False
131 | else:
132 | toSend = toSend + "%2.3f: %s \n" % (s[1],s[0])
133 | lastTime = curTime
134 | print "%d,%s" % (curTime,sorted_P_bayes[0][0])
135 | fifo.popleft()
136 | fifo.append(int(sorted_P_bayes[0][0]))
137 | a = numpy.array(fifo)
138 | counts = numpy.bincount(a)
139 | foo = "Best of 5: %d\n" % (numpy.argmax(counts))
140 | toSend = foo + toSend
141 | sendState(toSend)
142 |
143 | ws.close()
144 |
--------------------------------------------------------------------------------
/RaspberryPi/update.php:
--------------------------------------------------------------------------------
1 | setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
39 | $query = "
40 | INSERT INTO locations (
41 | mac,
42 | rssi,
43 | room,
44 | time
45 | ) VALUES (
46 | :mac,
47 | :rssi,
48 | :room,
49 | :time
50 | )
51 | ";
52 |
53 | $stmt = $db->prepare($query);
54 | $stmt->bindValue(':mac', (string) $mac, SQLITE3_TEXT);
55 | $stmt->bindValue(':rssi', (float) $rssi, SQLITE3_INTEGER);
56 | $stmt->bindValue(':room', (float) $room, SQLITE3_INTEGER);
57 | $stmt->bindValue(':time', (float) $time, SQLITE3_INTEGER);
58 | $stmt->execute();
59 | // close database
60 | $db = null;
61 | }
62 | catch(Exception $e) {
63 | //print $e;
64 | }
65 | }
66 | }
67 |
68 |
69 | // read the POST body
70 | $request_body = file_get_contents('php://input');
71 |
72 | // decode the JSON
73 | $data_points = json_decode($request_body, true);
74 |
75 | // loop over the elements of the array, inserting each one into the db
76 | $num_points = 0;
77 | foreach ($data_points as $data_point) {
78 | insert_data_point($data_point);
79 | $num_points++;
80 | }
81 |
82 | // respond with the number of points we inserted
83 | echo $num_points;
84 |
85 | // TODO: add gzip compression support
86 | // TODO: send http_response_code(400) for bad requests
87 |
88 | ?>
89 |
--------------------------------------------------------------------------------