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