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