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