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