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