altosdroid: stop sending device name, just send config data
[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 AltosConfigData mConfigData      = null;
72         private TelemetryReader mTelemetryReader = null;
73
74         // internally track state of bluetooth connection
75         private int state = STATE_NONE;
76
77         // Handler of incoming messages from clients.
78         static class IncomingHandler extends Handler {
79                 private final WeakReference<TelemetryService> service;
80                 IncomingHandler(TelemetryService s) { service = new WeakReference<TelemetryService>(s); }
81
82                 @Override
83                 public void handleMessage(Message msg) {
84                         TelemetryService s = service.get();
85                         switch (msg.what) {
86                         case MSG_REGISTER_CLIENT:
87                                 s.mClients.add(msg.replyTo);
88                                 try {
89                                         // Now we try to send the freshly connected UI any relavant information about what
90                                         // we're talking to - Basically state and Config Data.
91                                         msg.replyTo.send(Message.obtain(null, AltosDroid.MSG_STATE_CHANGE, s.state, -1, s.mConfigData));
92                                 } catch (RemoteException e) {
93                                         s.mClients.remove(msg.replyTo);
94                                 }
95                                 if (D) Log.d(TAG, "Client bound to service");
96                                 break;
97                         case MSG_UNREGISTER_CLIENT:
98                                 s.mClients.remove(msg.replyTo);
99                                 if (D) Log.d(TAG, "Client unbound from service");
100                                 break;
101                         case MSG_CONNECT:
102                                 if (D) Log.d(TAG, "Connect command received");
103                                 s.device = (BluetoothDevice) msg.obj;
104                                 s.startAltosBluetooth();
105                                 break;
106                         case MSG_CONNECTED:
107                                 if (D) Log.d(TAG, "Connected to device");
108                                 s.connected();
109                                 break;
110                         case MSG_CONNECT_FAILED:
111                                 if (D) Log.d(TAG, "Connection failed... retrying");
112                                 s.startAltosBluetooth();
113                                 break;
114                         case MSG_DISCONNECTED:
115                                 // Only do the following if we haven't been shutdown elsewhere..
116                                 if (s.device != null) {
117                                         if (D) Log.d(TAG, "Disconnected from " + s.device.getName());
118                                         s.stopAltosBluetooth();
119                                 }
120                                 break;
121                         case MSG_TELEMETRY:
122                                 s.sendMessageToClients(Message.obtain(null, AltosDroid.MSG_TELEMETRY, msg.obj));
123                                 break;
124                         default:
125                                 super.handleMessage(msg);
126                         }
127                 }
128         }
129
130         private void sendMessageToClients(Message m) {
131                 for (int i=mClients.size()-1; i>=0; i--) {
132                         try {
133                                 mClients.get(i).send(m);
134                         } catch (RemoteException e) {
135                                 mClients.remove(i);
136                         }
137                 }
138         }
139
140         private void stopAltosBluetooth() {
141                 if (D) Log.d(TAG, "stopAltosBluetooth(): begin");
142                 setState(STATE_READY);
143                 if (mTelemetryReader != null) {
144                         if (D) Log.d(TAG, "stopAltosBluetooth(): stopping TelemetryReader");
145                         mTelemetryReader.interrupt();
146                         try {
147                                 mTelemetryReader.join();
148                         } catch (InterruptedException e) {
149                         }
150                         mTelemetryReader = null;
151                 }
152                 if (mAltosBluetooth != null) {
153                         if (D) Log.d(TAG, "stopAltosBluetooth(): stopping AltosBluetooth");
154                         mAltosBluetooth.close();
155                         mAltosBluetooth = null;
156                 }
157                 device = null;
158                 mConfigData = null;
159         }
160
161         private void startAltosBluetooth() {
162                 if (mAltosBluetooth == null) {
163                         if (D) Log.d(TAG, String.format("startAltosBluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress()));
164                         mAltosBluetooth = new AltosBluetooth(device, mHandler);
165                         setState(STATE_CONNECTING);
166                 } else {
167                         // This is a bit of a hack - if it appears we're still connected, we treat this as a restart.
168                         // So, to give a suitable delay to teardown/bringup, we just schedule a resend of a message
169                         // to ourselves in a few seconds time that will ultimately call this method again.
170                         // ... then we tear down the existing connection.
171                         // We do it this way around so that we don't lose a reference to the device when this method
172                         // is called on reception of MSG_CONNECT_FAILED in the handler above.
173                         mHandler.sendMessageDelayed(Message.obtain(null, MSG_CONNECT, device), 3000);
174                         stopAltosBluetooth();
175                 }
176         }
177
178         private synchronized void setState(int s) {
179                 if (D) Log.d(TAG, "setState(): " + state + " -> " + s);
180                 state = s;
181
182                 // This shouldn't be required - mConfigData should be null for any non-connected
183                 // state, but to be safe and to reduce message size
184                 AltosConfigData acd = (state == STATE_CONNECTED) ? mConfigData : null;
185
186                 sendMessageToClients(Message.obtain(null, AltosDroid.MSG_STATE_CHANGE, state, -1, acd));
187         }
188
189         private void connected() {
190                 try {
191                         mConfigData = mAltosBluetooth.config_data();
192                 } catch (InterruptedException e) {
193                 } catch (TimeoutException e) {
194                         // If this timed out, then we really want to retry it, but
195                         // probably safer to just retry the connection from scratch.
196                         mHandler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
197                         return;
198                 }
199
200                 setState(STATE_CONNECTED);
201
202                 mTelemetryReader = new TelemetryReader(mAltosBluetooth, mHandler);
203                 mTelemetryReader.start();
204         }
205
206
207         @Override
208         public void onCreate() {
209                 // Create a reference to the NotificationManager so that we can update our notifcation text later
210                 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
211
212                 setState(STATE_READY);
213         }
214
215         @Override
216         public int onStartCommand(Intent intent, int flags, int startId) {
217                 Log.i("TelemetryService", "Received start id " + startId + ": " + intent);
218
219                 CharSequence text = getText(R.string.telemetry_service_started);
220
221                 // Create notification to be displayed while the service runs
222                 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
223
224                 // The PendingIntent to launch our activity if the user selects this notification
225                 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
226                                 new Intent(this, AltosDroid.class), 0);
227
228                 // Set the info for the views that show in the notification panel.
229                 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
230
231                 // Set the notification to be in the "Ongoing" section.
232                 notification.flags |= Notification.FLAG_ONGOING_EVENT;
233
234                 // Move us into the foreground.
235                 startForeground(NOTIFICATION, notification);
236
237                 // We want this service to continue running until it is explicitly
238                 // stopped, so return sticky.
239                 return START_STICKY;
240         }
241
242         @Override
243         public void onDestroy() {
244
245                 // Stop the bluetooth Comms threads
246                 stopAltosBluetooth();
247
248                 // Demote us from the foreground, and cancel the persistent notification.
249                 stopForeground(true);
250
251                 // Tell the user we stopped.
252                 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
253         }
254
255         @Override
256         public IBinder onBind(Intent intent) {
257                 return mMessenger.getBinder();
258         }
259
260
261 }