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