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