altosdroid: Send LOCATION and CRC_ERROR messages to UI.
[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         TelemetryService service;
49         boolean fine;
50
51         public void onLocationChanged(Location location) {
52                 service.sendLocation(location);
53         }
54
55         public void onStatusChanged(String provider, int status, Bundle extras) {
56         }
57
58         public void onProviderEnabled(String provider) {
59         }
60
61         public void onProviderDisabled(String provider) {
62         }
63
64         public AltosLocationListener(TelemetryService service, boolean fine) {
65                 this.fine = fine;
66                 this.service = service;
67         }
68 }
69
70 public class TelemetryService extends Service {
71
72         private static final String TAG = "TelemetryService";
73         private static final boolean D = true;
74
75         static final int MSG_REGISTER_CLIENT   = 1;
76         static final int MSG_UNREGISTER_CLIENT = 2;
77         static final int MSG_CONNECT           = 3;
78         static final int MSG_CONNECTED         = 4;
79         static final int MSG_CONNECT_FAILED    = 5;
80         static final int MSG_DISCONNECTED      = 6;
81         static final int MSG_TELEMETRY         = 7;
82         static final int MSG_SETFREQUENCY      = 8;
83         static final int MSG_LOCATION          = 9;
84         static final int MSG_CRC_ERROR         = 10;
85
86         public static final int STATE_NONE       = 0;
87         public static final int STATE_READY      = 1;
88         public static final int STATE_CONNECTING = 2;
89         public static final int STATE_CONNECTED  = 3;
90
91         // Unique Identification Number for the Notification.
92         // We use it on Notification start, and to cancel it.
93         private int NOTIFICATION = R.string.telemetry_service_label;
94         //private NotificationManager mNM;
95
96         // Timer - we wake up every now and then to decide if the service should stop
97         private Timer timer = new Timer();
98
99         ArrayList<Messenger> mClients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
100         final Handler   mHandler   = new IncomingHandler(this);
101         final Messenger mMessenger = new Messenger(mHandler); // Target we publish for clients to send messages to IncomingHandler.
102
103         // Name of the connected device
104         private BluetoothDevice device           = null;
105         private AltosBluetooth  mAltosBluetooth  = null;
106         private AltosConfigData mConfigData      = null;
107         private TelemetryReader mTelemetryReader = null;
108         private TelemetryLogger mTelemetryLogger = null;
109
110         // internally track state of bluetooth connection
111         private int state = STATE_NONE;
112
113         // location listeners
114
115         private AltosLocationListener gpsListener;
116         private AltosLocationListener netListener;
117         
118         // Last data seen; send to UI when it starts
119
120         private AltosState last_state;
121         private Location last_location;
122         private int last_crc_errors;
123
124         // Handler of incoming messages from clients.
125         static class IncomingHandler extends Handler {
126                 private final WeakReference<TelemetryService> service;
127                 IncomingHandler(TelemetryService s) { service = new WeakReference<TelemetryService>(s); }
128
129                 @Override
130                 public void handleMessage(Message msg) {
131                         TelemetryService s = service.get();
132                         switch (msg.what) {
133                         case MSG_REGISTER_CLIENT:
134                                 s.mClients.add(msg.replyTo);
135                                 try {
136                                         // Now we try to send the freshly connected UI any relavant information about what
137                                         // we're talking to - Basically state and Config Data.
138                                         msg.replyTo.send(Message.obtain(null, AltosDroid.MSG_STATE_CHANGE, s.state, -1, s.mConfigData));
139                                 } catch (RemoteException e) {
140                                         s.mClients.remove(msg.replyTo);
141                                 }
142                                 if (D) Log.d(TAG, "Client bound to service");
143                                 if (s.last_state != null)
144                                         s.sendTelemetry(s.last_state);
145                                 if (s.last_location != null)
146                                         s.sendLocation(s.last_location);
147                                 if (s.last_crc_errors != 0)
148                                         s.sendCrcErrors(s.last_crc_errors);
149                                 break;
150                         case MSG_UNREGISTER_CLIENT:
151                                 s.mClients.remove(msg.replyTo);
152                                 if (D) Log.d(TAG, "Client unbound from service");
153                                 break;
154                         case MSG_CONNECT:
155                                 if (D) Log.d(TAG, "Connect command received");
156                                 s.device = (BluetoothDevice) msg.obj;
157                                 s.startAltosBluetooth();
158                                 break;
159                         case MSG_CONNECTED:
160                                 if (D) Log.d(TAG, "Connected to device");
161                                 s.connected();
162                                 break;
163                         case MSG_CONNECT_FAILED:
164                                 if (D) Log.d(TAG, "Connection failed... retrying");
165                                 s.startAltosBluetooth();
166                                 break;
167                         case MSG_DISCONNECTED:
168                                 // Only do the following if we haven't been shutdown elsewhere..
169                                 if (s.device != null) {
170                                         if (D) Log.d(TAG, "Disconnected from " + s.device.getName());
171                                         s.stopAltosBluetooth();
172                                 }
173                                 break;
174                         case MSG_TELEMETRY:
175                                 s.sendMessageToClients(Message.obtain(null, AltosDroid.MSG_TELEMETRY, msg.obj));
176                                 break;
177                         case MSG_SETFREQUENCY:
178                                 if (s.state == STATE_CONNECTED) {
179                                         try {
180                                                 s.mAltosBluetooth.set_radio_frequency((Double) msg.obj);
181                                         } catch (InterruptedException e) {
182                                         } catch (TimeoutException e) {
183                                         }
184                                 }
185                                 break;
186                         default:
187                                 super.handleMessage(msg);
188                         }
189                 }
190         }
191
192         public void sendTelemetry(AltosState state) {
193                 last_state = state;
194                 mHandler.obtainMessage(MSG_TELEMETRY, state).sendToTarget();
195         }
196
197         public void sendLocation(Location location) {
198                 last_location = location;
199                 mHandler.obtainMessage(MSG_LOCATION, location).sendToTarget();
200         }
201
202         public void sendCrcErrors(int crc_errors) {
203                 last_crc_errors = crc_errors;
204                 mHandler.obtainMessage(MSG_CRC_ERROR, new Integer(crc_errors)).sendToTarget();
205         }
206
207         private void sendMessageToClients(Message m) {
208                 for (int i=mClients.size()-1; i>=0; i--) {
209                         try {
210                                 mClients.get(i).send(m);
211                         } catch (RemoteException e) {
212                                 mClients.remove(i);
213                         }
214                 }
215         }
216
217         private void stopAltosBluetooth() {
218                 if (D) Log.d(TAG, "stopAltosBluetooth(): begin");
219                 setState(STATE_READY);
220                 if (mTelemetryReader != null) {
221                         if (D) Log.d(TAG, "stopAltosBluetooth(): stopping TelemetryReader");
222                         mTelemetryReader.interrupt();
223                         try {
224                                 mTelemetryReader.join();
225                         } catch (InterruptedException e) {
226                         }
227                         mTelemetryReader = null;
228                 }
229                 if (mTelemetryLogger != null) {
230                         if (D) Log.d(TAG, "stopAltosBluetooth(): stopping TelemetryLogger");
231                         mTelemetryLogger.stop();
232                         mTelemetryLogger = null;
233                 }
234                 if (mAltosBluetooth != null) {
235                         if (D) Log.d(TAG, "stopAltosBluetooth(): stopping AltosBluetooth");
236                         mAltosBluetooth.close();
237                         mAltosBluetooth = null;
238                 }
239                 device = null;
240                 mConfigData = null;
241         }
242
243         private void startAltosBluetooth() {
244                 if (mAltosBluetooth == null) {
245                         if (D) Log.d(TAG, String.format("startAltosBluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress()));
246                         mAltosBluetooth = new AltosBluetooth(device, mHandler);
247                         setState(STATE_CONNECTING);
248                 } else {
249                         // This is a bit of a hack - if it appears we're still connected, we treat this as a restart.
250                         // So, to give a suitable delay to teardown/bringup, we just schedule a resend of a message
251                         // to ourselves in a few seconds time that will ultimately call this method again.
252                         // ... then we tear down the existing connection.
253                         // We do it this way around so that we don't lose a reference to the device when this method
254                         // is called on reception of MSG_CONNECT_FAILED in the handler above.
255                         mHandler.sendMessageDelayed(Message.obtain(null, MSG_CONNECT, device), 3000);
256                         stopAltosBluetooth();
257                 }
258         }
259
260         private synchronized void setState(int s) {
261                 if (D) Log.d(TAG, "setState(): " + state + " -> " + s);
262                 state = s;
263
264                 // This shouldn't be required - mConfigData should be null for any non-connected
265                 // state, but to be safe and to reduce message size
266                 AltosConfigData acd = (state == STATE_CONNECTED) ? mConfigData : null;
267
268                 sendMessageToClients(Message.obtain(null, AltosDroid.MSG_STATE_CHANGE, state, -1, acd));
269         }
270
271         private void connected() {
272                 try {
273                         mConfigData = mAltosBluetooth.config_data();
274                 } catch (InterruptedException e) {
275                 } catch (TimeoutException e) {
276                         // If this timed out, then we really want to retry it, but
277                         // probably safer to just retry the connection from scratch.
278                         mHandler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
279                         return;
280                 }
281
282                 setState(STATE_CONNECTED);
283
284                 mTelemetryReader = new TelemetryReader(this, mAltosBluetooth, mHandler);
285                 mTelemetryReader.start();
286                 
287                 mTelemetryLogger = new TelemetryLogger(this, mAltosBluetooth);
288         }
289
290
291         private void onTimerTick() {
292                 if (D) Log.d(TAG, "Timer wakeup");
293                 try {
294                         if (mClients.size() <= 0 && state != STATE_CONNECTED) {
295                                 stopSelf();
296                         }
297                 } catch (Throwable t) {
298                         Log.e(TAG, "Timer failed: ", t);
299                 }
300         }
301
302
303         @Override
304         public void onCreate() {
305                 // Create a reference to the NotificationManager so that we can update our notifcation text later
306                 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
307
308                 setState(STATE_READY);
309
310                 // Start our timer - first event in 10 seconds, then every 10 seconds after that.
311                 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 10000L, 10000L);
312
313                 // Listen for GPS and Network position updates
314                 gpsListener = new AltosLocationListener(this, true);
315                 netListener = new AltosLocationListener(this, false);
316
317                 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
318                 
319                 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpsListener);
320                 locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, netListener);
321         }
322
323         @Override
324         public int onStartCommand(Intent intent, int flags, int startId) {
325                 Log.i("TelemetryService", "Received start id " + startId + ": " + intent);
326
327                 CharSequence text = getText(R.string.telemetry_service_started);
328
329                 // Create notification to be displayed while the service runs
330                 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
331
332                 // The PendingIntent to launch our activity if the user selects this notification
333                 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
334                                 new Intent(this, AltosDroid.class), 0);
335
336                 // Set the info for the views that show in the notification panel.
337                 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
338
339                 // Set the notification to be in the "Ongoing" section.
340                 notification.flags |= Notification.FLAG_ONGOING_EVENT;
341
342                 // Move us into the foreground.
343                 startForeground(NOTIFICATION, notification);
344
345                 // We want this service to continue running until it is explicitly
346                 // stopped, so return sticky.
347                 return START_STICKY;
348         }
349
350         @Override
351         public void onDestroy() {
352
353                 // Stop listening for location updates
354                 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
355                 locationManager.removeUpdates(gpsListener);
356                 locationManager.removeUpdates(netListener);
357
358                 // Stop the bluetooth Comms threads
359                 stopAltosBluetooth();
360
361                 // Demote us from the foreground, and cancel the persistent notification.
362                 stopForeground(true);
363
364                 // Stop our timer
365                 if (timer != null) {timer.cancel();}
366
367                 // Tell the user we stopped.
368                 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
369         }
370
371         @Override
372         public IBinder onBind(Intent intent) {
373                 return mMessenger.getBinder();
374         }
375
376
377 }