altosdroid: fix a connection retry having a null pointer
[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
24 import android.app.Notification;
25 //import android.app.NotificationManager;
26 import android.app.PendingIntent;
27 import android.app.Service;
28 import android.bluetooth.BluetoothDevice;
29 import android.content.Intent;
30 //import android.os.Bundle;
31 import android.os.IBinder;
32 import android.os.Handler;
33 import android.os.Message;
34 import android.os.Messenger;
35 import android.os.RemoteException;
36 import android.util.Log;
37 import android.widget.Toast;
38
39 //import org.altusmetrum.AltosLib.*;
40
41 public class TelemetryService extends Service {
42
43         private static final String TAG = "TelemetryService";
44         private static final boolean D = true;
45
46         static final int MSG_REGISTER_CLIENT   = 1;
47         static final int MSG_UNREGISTER_CLIENT = 2;
48         static final int MSG_CONNECT           = 3;
49         static final int MSG_CONNECTED         = 4;
50         static final int MSG_CONNECT_FAILED    = 5;
51         static final int MSG_DISCONNECTED      = 6;
52         static final int MSG_TELEMETRY         = 7;
53
54         public static final int STATE_NONE       = 0;
55         public static final int STATE_READY      = 1;
56         public static final int STATE_CONNECTING = 2;
57         public static final int STATE_CONNECTED  = 3;
58
59         // Unique Identification Number for the Notification.
60         // We use it on Notification start, and to cancel it.
61         private int NOTIFICATION = R.string.telemetry_service_label;
62         //private NotificationManager mNM;
63
64         ArrayList<Messenger> mClients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
65         final Handler   mHandler   = new IncomingHandler(this);
66         final Messenger mMessenger = new Messenger(mHandler); // Target we publish for clients to send messages to IncomingHandler.
67
68         // Name of the connected device
69         private BluetoothDevice device = null;
70         private AltosBluetooth mAltosBluetooth = null;
71         private TelemetryReader mTelemetryReader = null;
72
73         // internally track state of bluetooth connection
74         private int state = STATE_NONE;
75
76         // Handler of incoming messages from clients.
77         static class IncomingHandler extends Handler {
78                 private final WeakReference<TelemetryService> service;
79                 IncomingHandler(TelemetryService s) { service = new WeakReference<TelemetryService>(s); }
80
81                 @Override
82                 public void handleMessage(Message msg) {
83                         TelemetryService s = service.get();
84                         switch (msg.what) {
85                         case MSG_REGISTER_CLIENT:
86                                 s.mClients.add(msg.replyTo);
87                                 try {
88                                         msg.replyTo.send(Message.obtain(null, AltosDroid.MSG_DEVNAME, s.device.getName()));
89                                         msg.replyTo.send(Message.obtain(null, AltosDroid.MSG_STATE_CHANGE, s.state, -1));
90                                 } catch (RemoteException e) {
91                                         s.mClients.remove(msg.replyTo);
92                                 }
93                                 if (D) Log.d(TAG, "Client bound to service");
94                                 break;
95                         case MSG_UNREGISTER_CLIENT:
96                                 s.mClients.remove(msg.replyTo);
97                                 if (D) Log.d(TAG, "Client unbound from service");
98                                 break;
99                         case MSG_CONNECT:
100                                 if (D) Log.d(TAG, "Connect command received");
101                                 s.device = (BluetoothDevice) msg.obj;
102                                 s.startAltosBluetooth();
103                                 break;
104                         case MSG_CONNECTED:
105                                 if (D) Log.d(TAG, "Connected to device");
106                                 s.connected();
107                                 break;
108                         case MSG_CONNECT_FAILED:
109                                 if (D) Log.d(TAG, "Connection failed... retrying");
110                                 s.startAltosBluetooth();
111                                 break;
112                         case MSG_DISCONNECTED:
113                                 // Only do the following if we haven't been shutdown elsewhere..
114                                 if (s.device != null) {
115                                         if (D) Log.d(TAG, "Disconnected from " + s.device.getName());
116                                         s.stopAltosBluetooth();
117                                 }
118                                 break;
119                         case MSG_TELEMETRY:
120                                 s.sendMessageToClients(Message.obtain(null, AltosDroid.MSG_TELEMETRY, msg.obj));
121                                 break;
122                         default:
123                                 super.handleMessage(msg);
124                         }
125                 }
126         }
127
128         private void sendMessageToClients(Message m) {
129                 for (int i=mClients.size()-1; i>=0; i--) {
130                         try {
131                                 mClients.get(i).send(m);
132                         } catch (RemoteException e) {
133                                 mClients.remove(i);
134                         }
135                 }
136         }
137
138         private void stopAltosBluetooth() {
139                 if (D) Log.d(TAG, "stopAltosBluetooth(): begin");
140                 setState(STATE_READY);
141                 if (mTelemetryReader != null) {
142                         if (D) Log.d(TAG, "stopAltosBluetooth(): stopping TelemetryReader");
143                         mTelemetryReader.interrupt();
144                         try {
145                                 mTelemetryReader.join();
146                         } catch (InterruptedException e) {
147                         }
148                         mTelemetryReader = null;
149                 }
150                 if (mAltosBluetooth != null) {
151                         if (D) Log.d(TAG, "stopAltosBluetooth(): stopping AltosBluetooth");
152                         mAltosBluetooth.close();
153                         mAltosBluetooth = null;
154                 }
155                 device = null;
156         }
157
158         private void startAltosBluetooth() {
159                 if (mAltosBluetooth == null) {
160                         if (D) Log.d(TAG, String.format("startAltosBluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress()));
161                         mAltosBluetooth = new AltosBluetooth(device, mHandler);
162                         setState(STATE_CONNECTING);
163                 } else {
164                         // This is a bit of a hack - if it appears we're still connected, we treat this as a restart.
165                         // So, to give a suitable delay to teardown/bringup, we just schedule a resend of a message
166                         // to ourselves in a few seconds time that will ultimately call this method again.
167                         // ... then we tear down the existing connection.
168                         // We do it this way around so that we don't lose a reference to the device when this method
169                         // is called on reception of MSG_CONNECT_FAILED in the handler above.
170                         mHandler.sendMessageDelayed(Message.obtain(null, MSG_CONNECT, device), 3000);
171                         stopAltosBluetooth();
172                 }
173         }
174
175         private synchronized void setState(int s) {
176                 if (D) Log.d(TAG, "setState(): " + state + " -> " + s);
177                 state = s;
178
179                 sendMessageToClients(Message.obtain(null, AltosDroid.MSG_STATE_CHANGE, state, -1));
180         }
181
182         private void connected() {
183                 sendMessageToClients(Message.obtain(null, AltosDroid.MSG_DEVNAME, device.getName()));
184                 setState(STATE_CONNECTED);
185                 try {
186                         sendMessageToClients(Message.obtain(null, AltosDroid.MSG_DEVCONFIG, mAltosBluetooth.config_data()));
187                 } catch (InterruptedException e) {
188                 } catch (TimeoutException e) {
189                 }
190                 mTelemetryReader = new TelemetryReader(mAltosBluetooth, mHandler);
191                 mTelemetryReader.start();
192         }
193
194
195         @Override
196         public void onCreate() {
197                 // Create a reference to the NotificationManager so that we can update our notifcation text later
198                 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
199
200                 setState(STATE_READY);
201         }
202
203         @Override
204         public int onStartCommand(Intent intent, int flags, int startId) {
205                 Log.i("TelemetryService", "Received start id " + startId + ": " + intent);
206
207                 CharSequence text = getText(R.string.telemetry_service_started);
208
209                 // Create notification to be displayed while the service runs
210                 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
211
212                 // The PendingIntent to launch our activity if the user selects this notification
213                 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
214                                 new Intent(this, AltosDroid.class), 0);
215
216                 // Set the info for the views that show in the notification panel.
217                 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
218
219                 // Set the notification to be in the "Ongoing" section.
220                 notification.flags |= Notification.FLAG_ONGOING_EVENT;
221
222                 // Move us into the foreground.
223                 startForeground(NOTIFICATION, notification);
224
225                 // We want this service to continue running until it is explicitly
226                 // stopped, so return sticky.
227                 return START_STICKY;
228         }
229
230         @Override
231         public void onDestroy() {
232
233                 // Stop the bluetooth Comms threads
234                 stopAltosBluetooth();
235
236                 // Demote us from the foreground, and cancel the persistent notification.
237                 stopForeground(true);
238
239                 // Tell the user we stopped.
240                 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
241         }
242
243         @Override
244         public IBinder onBind(Intent intent) {
245                 return mMessenger.getBinder();
246         }
247
248
249 }