altosdroid: Hook up the position listeners
[fw/altos] / altosdroid / src / org / altusmetrum / AltosDroid / TelemetryService.java
1 /*
2  * Copyright © 2012 Mike Beattie <mike@ethernal.org>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 package org.altusmetrum.AltosDroid;
19
20 import java.lang.ref.WeakReference;
21 import java.util.ArrayList;
22 import java.util.concurrent.TimeoutException;
23 import java.util.Timer;
24 import java.util.TimerTask;
25
26 import android.app.Notification;
27 //import android.app.NotificationManager;
28 import android.app.PendingIntent;
29 import android.app.Service;
30 import android.bluetooth.BluetoothDevice;
31 import android.content.Intent;
32 import android.content.Context;
33 import android.os.Bundle;
34 import android.os.IBinder;
35 import android.os.Handler;
36 import android.os.Message;
37 import android.os.Messenger;
38 import android.os.RemoteException;
39 import android.util.Log;
40 import android.widget.Toast;
41 import android.location.Location;
42 import android.location.LocationManager;
43 import android.location.LocationListener;
44
45 import org.altusmetrum.altoslib_1.*;
46
47 class AltosLocationListener implements LocationListener {
48         boolean fine;
49
50         public void onLocationChanged(Location location) {
51         }
52
53         public void onStatusChanged(String provider, int status, Bundle extras) {
54         }
55
56         public void onProviderEnabled(String provider) {
57         }
58
59         public void onProviderDisabled(String provider) {
60         }
61
62         public AltosLocationListener(boolean fine) {
63                 this.fine = fine;
64         }
65 }
66
67 public class TelemetryService extends Service {
68
69         private static final String TAG = "TelemetryService";
70         private static final boolean D = true;
71
72         static final int MSG_REGISTER_CLIENT   = 1;
73         static final int MSG_UNREGISTER_CLIENT = 2;
74         static final int MSG_CONNECT           = 3;
75         static final int MSG_CONNECTED         = 4;
76         static final int MSG_CONNECT_FAILED    = 5;
77         static final int MSG_DISCONNECTED      = 6;
78         static final int MSG_TELEMETRY         = 7;
79         static final int MSG_SETFREQUENCY      = 8;
80
81         public static final int STATE_NONE       = 0;
82         public static final int STATE_READY      = 1;
83         public static final int STATE_CONNECTING = 2;
84         public static final int STATE_CONNECTED  = 3;
85
86         // Unique Identification Number for the Notification.
87         // We use it on Notification start, and to cancel it.
88         private int NOTIFICATION = R.string.telemetry_service_label;
89         //private NotificationManager mNM;
90
91         // Timer - we wake up every now and then to decide if the service should stop
92         private Timer timer = new Timer();
93
94         ArrayList<Messenger> mClients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
95         final Handler   mHandler   = new IncomingHandler(this);
96         final Messenger mMessenger = new Messenger(mHandler); // Target we publish for clients to send messages to IncomingHandler.
97
98         // Name of the connected device
99         private BluetoothDevice device           = null;
100         private AltosBluetooth  mAltosBluetooth  = null;
101         private AltosConfigData mConfigData      = null;
102         private TelemetryReader mTelemetryReader = null;
103         private TelemetryLogger mTelemetryLogger = null;
104
105         // internally track state of bluetooth connection
106         private int state = STATE_NONE;
107
108         // location listeners
109
110         private AltosLocationListener gpsListener;
111         private AltosLocationListener netListener;
112         
113         // Handler of incoming messages from clients.
114         static class IncomingHandler extends Handler {
115                 private final WeakReference<TelemetryService> service;
116                 IncomingHandler(TelemetryService s) { service = new WeakReference<TelemetryService>(s); }
117
118                 @Override
119                 public void handleMessage(Message msg) {
120                         TelemetryService s = service.get();
121                         switch (msg.what) {
122                         case MSG_REGISTER_CLIENT:
123                                 s.mClients.add(msg.replyTo);
124                                 try {
125                                         // Now we try to send the freshly connected UI any relavant information about what
126                                         // we're talking to - Basically state and Config Data.
127                                         msg.replyTo.send(Message.obtain(null, AltosDroid.MSG_STATE_CHANGE, s.state, -1, s.mConfigData));
128                                 } catch (RemoteException e) {
129                                         s.mClients.remove(msg.replyTo);
130                                 }
131                                 if (D) Log.d(TAG, "Client bound to service");
132                                 break;
133                         case MSG_UNREGISTER_CLIENT:
134                                 s.mClients.remove(msg.replyTo);
135                                 if (D) Log.d(TAG, "Client unbound from service");
136                                 break;
137                         case MSG_CONNECT:
138                                 if (D) Log.d(TAG, "Connect command received");
139                                 s.device = (BluetoothDevice) msg.obj;
140                                 s.startAltosBluetooth();
141                                 break;
142                         case MSG_CONNECTED:
143                                 if (D) Log.d(TAG, "Connected to device");
144                                 s.connected();
145                                 break;
146                         case MSG_CONNECT_FAILED:
147                                 if (D) Log.d(TAG, "Connection failed... retrying");
148                                 s.startAltosBluetooth();
149                                 break;
150                         case MSG_DISCONNECTED:
151                                 // Only do the following if we haven't been shutdown elsewhere..
152                                 if (s.device != null) {
153                                         if (D) Log.d(TAG, "Disconnected from " + s.device.getName());
154                                         s.stopAltosBluetooth();
155                                 }
156                                 break;
157                         case MSG_TELEMETRY:
158                                 s.sendMessageToClients(Message.obtain(null, AltosDroid.MSG_TELEMETRY, msg.obj));
159                                 break;
160                         case MSG_SETFREQUENCY:
161                                 if (s.state == STATE_CONNECTED) {
162                                         try {
163                                                 s.mAltosBluetooth.set_radio_frequency((Double) msg.obj);
164                                         } catch (InterruptedException e) {
165                                         } catch (TimeoutException e) {
166                                         }
167                                 }
168                                 break;
169                         default:
170                                 super.handleMessage(msg);
171                         }
172                 }
173         }
174
175         private void sendMessageToClients(Message m) {
176                 for (int i=mClients.size()-1; i>=0; i--) {
177                         try {
178                                 mClients.get(i).send(m);
179                         } catch (RemoteException e) {
180                                 mClients.remove(i);
181                         }
182                 }
183         }
184
185         private void stopAltosBluetooth() {
186                 if (D) Log.d(TAG, "stopAltosBluetooth(): begin");
187                 setState(STATE_READY);
188                 if (mTelemetryReader != null) {
189                         if (D) Log.d(TAG, "stopAltosBluetooth(): stopping TelemetryReader");
190                         mTelemetryReader.interrupt();
191                         try {
192                                 mTelemetryReader.join();
193                         } catch (InterruptedException e) {
194                         }
195                         mTelemetryReader = null;
196                 }
197                 if (mTelemetryLogger != null) {
198                         if (D) Log.d(TAG, "stopAltosBluetooth(): stopping TelemetryLogger");
199                         mTelemetryLogger.stop();
200                         mTelemetryLogger = null;
201                 }
202                 if (mAltosBluetooth != null) {
203                         if (D) Log.d(TAG, "stopAltosBluetooth(): stopping AltosBluetooth");
204                         mAltosBluetooth.close();
205                         mAltosBluetooth = null;
206                 }
207                 device = null;
208                 mConfigData = null;
209         }
210
211         private void startAltosBluetooth() {
212                 if (mAltosBluetooth == null) {
213                         if (D) Log.d(TAG, String.format("startAltosBluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress()));
214                         mAltosBluetooth = new AltosBluetooth(device, mHandler);
215                         setState(STATE_CONNECTING);
216                 } else {
217                         // This is a bit of a hack - if it appears we're still connected, we treat this as a restart.
218                         // So, to give a suitable delay to teardown/bringup, we just schedule a resend of a message
219                         // to ourselves in a few seconds time that will ultimately call this method again.
220                         // ... then we tear down the existing connection.
221                         // We do it this way around so that we don't lose a reference to the device when this method
222                         // is called on reception of MSG_CONNECT_FAILED in the handler above.
223                         mHandler.sendMessageDelayed(Message.obtain(null, MSG_CONNECT, device), 3000);
224                         stopAltosBluetooth();
225                 }
226         }
227
228         private synchronized void setState(int s) {
229                 if (D) Log.d(TAG, "setState(): " + state + " -> " + s);
230                 state = s;
231
232                 // This shouldn't be required - mConfigData should be null for any non-connected
233                 // state, but to be safe and to reduce message size
234                 AltosConfigData acd = (state == STATE_CONNECTED) ? mConfigData : null;
235
236                 sendMessageToClients(Message.obtain(null, AltosDroid.MSG_STATE_CHANGE, state, -1, acd));
237         }
238
239         private void connected() {
240                 try {
241                         mConfigData = mAltosBluetooth.config_data();
242                 } catch (InterruptedException e) {
243                 } catch (TimeoutException e) {
244                         // If this timed out, then we really want to retry it, but
245                         // probably safer to just retry the connection from scratch.
246                         mHandler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
247                         return;
248                 }
249
250                 setState(STATE_CONNECTED);
251
252                 mTelemetryReader = new TelemetryReader(mAltosBluetooth, mHandler);
253                 mTelemetryReader.start();
254                 
255                 mTelemetryLogger = new TelemetryLogger(this, mAltosBluetooth);
256         }
257
258
259         private void onTimerTick() {
260                 if (D) Log.d(TAG, "Timer wakeup");
261                 try {
262                         if (mClients.size() <= 0 && state != STATE_CONNECTED) {
263                                 stopSelf();
264                         }
265                 } catch (Throwable t) {
266                         Log.e(TAG, "Timer failed: ", t);
267                 }
268         }
269
270
271         @Override
272         public void onCreate() {
273                 // Create a reference to the NotificationManager so that we can update our notifcation text later
274                 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
275
276                 setState(STATE_READY);
277
278                 // Start our timer - first event in 10 seconds, then every 10 seconds after that.
279                 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 10000L, 10000L);
280
281                 // Listen for GPS and Network position updates
282                 gpsListener = new AltosLocationListener(true);
283                 netListener = new AltosLocationListener(false);
284
285                 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
286                 
287                 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpsListener);
288                 locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, netListener);
289         }
290
291         @Override
292         public int onStartCommand(Intent intent, int flags, int startId) {
293                 Log.i("TelemetryService", "Received start id " + startId + ": " + intent);
294
295                 CharSequence text = getText(R.string.telemetry_service_started);
296
297                 // Create notification to be displayed while the service runs
298                 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
299
300                 // The PendingIntent to launch our activity if the user selects this notification
301                 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
302                                 new Intent(this, AltosDroid.class), 0);
303
304                 // Set the info for the views that show in the notification panel.
305                 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
306
307                 // Set the notification to be in the "Ongoing" section.
308                 notification.flags |= Notification.FLAG_ONGOING_EVENT;
309
310                 // Move us into the foreground.
311                 startForeground(NOTIFICATION, notification);
312
313                 // We want this service to continue running until it is explicitly
314                 // stopped, so return sticky.
315                 return START_STICKY;
316         }
317
318         @Override
319         public void onDestroy() {
320
321                 // Stop listening for location updates
322                 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
323                 locationManager.removeUpdates(gpsListener);
324                 locationManager.removeUpdates(netListener);
325
326                 // Stop the bluetooth Comms threads
327                 stopAltosBluetooth();
328
329                 // Demote us from the foreground, and cancel the persistent notification.
330                 stopForeground(true);
331
332                 // Stop our timer
333                 if (timer != null) {timer.cancel();}
334
335                 // Tell the user we stopped.
336                 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
337         }
338
339         @Override
340         public IBinder onBind(Intent intent) {
341                 return mMessenger.getBinder();
342         }
343
344
345 }