5e34d610fa394404977d4a188ca9cc3b65d52991
[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_6.*;
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         ArrayList<Messenger> clients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
73         final Handler   handler   = new IncomingHandler(this);
74         final Messenger messenger = new Messenger(handler); // Target we publish for clients to send messages to IncomingHandler.
75
76         // Name of the connected device
77         DeviceAddress address;
78         private AltosBluetooth  altos_bluetooth  = null;
79         private TelemetryReader telemetry_reader = null;
80         private TelemetryLogger telemetry_logger = null;
81
82         // Local Bluetooth adapter
83         private BluetoothAdapter bluetooth_adapter = null;
84
85         // Last data seen; send to UI when it starts
86         private TelemetryState  telemetry_state;
87
88         // Handler of incoming messages from clients.
89         static class IncomingHandler extends Handler {
90                 private final WeakReference<TelemetryService> service;
91                 IncomingHandler(TelemetryService s) { service = new WeakReference<TelemetryService>(s); }
92
93                 @Override
94                 public void handleMessage(Message msg) {
95                         TelemetryService s = service.get();
96                         if (s == null)
97                                 return;
98                         switch (msg.what) {
99
100                                 /* Messages from application */
101                         case MSG_REGISTER_CLIENT:
102                                 s.add_client(msg.replyTo);
103                                 break;
104                         case MSG_UNREGISTER_CLIENT:
105                                 s.remove_client(msg.replyTo);
106                                 break;
107                         case MSG_CONNECT:
108                                 if (D) Log.d(TAG, "Connect command received");
109                                 DeviceAddress address = (DeviceAddress) msg.obj;
110                                 AltosDroidPreferences.set_active_device(address);
111                                 s.start_altos_bluetooth(address);
112                                 break;
113                         case MSG_SETFREQUENCY:
114                                 if (D) Log.d(TAG, "MSG_SETFREQUENCY");
115                                 s.telemetry_state.frequency = (Double) msg.obj;
116                                 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
117                                         try {
118                                                 s.altos_bluetooth.set_radio_frequency(s.telemetry_state.frequency);
119                                                 s.altos_bluetooth.save_frequency();
120                                         } catch (InterruptedException e) {
121                                         } catch (TimeoutException e) {
122                                         }
123                                 }
124                                 s.send_to_clients();
125                                 break;
126                         case MSG_SETBAUD:
127                                 if (D) Log.d(TAG, "MSG_SETBAUD");
128                                 s.telemetry_state.telemetry_rate = (Integer) msg.obj;
129                                 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
130                                         s.altos_bluetooth.set_telemetry_rate(s.telemetry_state.telemetry_rate);
131                                         s.altos_bluetooth.save_telemetry_rate();
132                                 }
133                                 s.send_to_clients();
134                                 break;
135
136                                 /*
137                                  *Messages from AltosBluetooth
138                                  */
139                         case MSG_CONNECTED:
140                                 if (D) Log.d(TAG, "Connected to device");
141                                 try {
142                                         s.connected();
143                                 } catch (InterruptedException ie) {
144                                 }
145                                 break;
146                         case MSG_CONNECT_FAILED:
147                                 if (s.address != null && !s.clients.isEmpty()) {
148                                         if (D) Log.d(TAG, "Connection failed... retrying");
149                                         s.start_altos_bluetooth(s.address);
150                                 } else {
151                                         s.stop_altos_bluetooth(true);
152                                 }
153                                 break;
154                         case MSG_DISCONNECTED:
155                                 Log.d(TAG, "MSG_DISCONNECTED");
156                                 if (s.address != null && !s.clients.isEmpty()) {
157                                         if (D) Log.d(TAG, "Connection lost... retrying");
158                                         s.start_altos_bluetooth(s.address);
159                                 } else {
160                                         s.stop_altos_bluetooth(true);
161                                 }
162                                 break;
163
164                                 /*
165                                  * Messages from TelemetryReader
166                                  */
167                         case MSG_TELEMETRY:
168                                 s.telemetry_state.state = (AltosState) msg.obj;
169                                 if (s.telemetry_state.state != null) {
170                                         if (D) Log.d(TAG, "Save state");
171                                         AltosPreferences.set_state(0, s.telemetry_state.state, null);
172                                 }
173                                 if (D) Log.d(TAG, "MSG_TELEMETRY");
174                                 s.send_to_clients();
175                                 break;
176                         case MSG_CRC_ERROR:
177                                 // forward crc error messages
178                                 s.telemetry_state.crc_errors = (Integer) msg.obj;
179                                 if (D) Log.d(TAG, "MSG_CRC_ERROR");
180                                 s.send_to_clients();
181                                 break;
182                         default:
183                                 super.handleMessage(msg);
184                         }
185                 }
186         }
187
188         /* Construct the message to deliver to clients
189          */
190         private Message message() {
191                 if (telemetry_state == null)
192                         Log.d(TAG, "telemetry_state null!");
193                 if (telemetry_state.state == null)
194                         Log.d(TAG, "telemetry_state.state null!");
195                 return Message.obtain(null, AltosDroid.MSG_STATE, telemetry_state);
196         }
197
198         /* A new friend has connected
199          */
200         private void add_client(Messenger client) {
201
202                 clients.add(client);
203                 if (D) Log.d(TAG, "Client bound to service");
204
205                 /* On connect, send the current state to the new client
206                  */
207                 send_to_client(client, message());
208
209                 /* If we've got an address from a previous session, then
210                  * go ahead and try to reconnect to the device
211                  */
212                 if (address != null && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
213                         if (D) Log.d(TAG, "Reconnecting now...");
214                         start_altos_bluetooth(address);
215                 }
216         }
217
218         /* A client has disconnected, clean up
219          */
220         private void remove_client(Messenger client) {
221                 clients.remove(client);
222                 if (D) Log.d(TAG, "Client unbound from service");
223
224                 /* When the list of clients is empty, stop the service if
225                  * we have no current telemetry source
226                  */
227
228                  if (clients.isEmpty() && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
229                          if (!D) Log.d(TAG, "No clients, no connection. Stopping\n");
230                          stopSelf();
231                  }
232         }
233
234         private void send_to_client(Messenger client, Message m) {
235                 try {
236                         if (D) Log.d(TAG, String.format("Send message to client %s", client.toString()));
237                         client.send(m);
238                 } catch (RemoteException e) {
239                         if (D) Log.e(TAG, String.format("Client %s disappeared", client.toString()));
240                         remove_client(client);
241                 }
242         }
243
244         private void send_to_clients() {
245                 Message m = message();
246                 if (D) Log.d(TAG, String.format("Send message to %d clients", clients.size()));
247                 for (Messenger client : clients)
248                         send_to_client(client, m);
249         }
250
251         private void stop_altos_bluetooth(boolean notify) {
252                 if (D) Log.d(TAG, "stop_altos_bluetooth(): begin");
253                 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
254                 telemetry_state.address = null;
255
256                 if (altos_bluetooth != null)
257                         altos_bluetooth.closing();
258
259                 if (telemetry_reader != null) {
260                         if (D) Log.d(TAG, "stop_altos_bluetooth(): stopping TelemetryReader");
261                         telemetry_reader.interrupt();
262                         try {
263                                 telemetry_reader.join();
264                         } catch (InterruptedException e) {
265                         }
266                         telemetry_reader = null;
267                 }
268                 if (telemetry_logger != null) {
269                         if (D) Log.d(TAG, "stop_altos_bluetooth(): stopping TelemetryLogger");
270                         telemetry_logger.stop();
271                         telemetry_logger = null;
272                 }
273                 if (altos_bluetooth != null) {
274                         if (D) Log.d(TAG, "stop_altos_bluetooth(): stopping AltosBluetooth");
275                         altos_bluetooth.close();
276                         altos_bluetooth = null;
277                 }
278                 telemetry_state.config = null;
279                 if (notify) {
280                         if (D) Log.d(TAG, "stop_altos_bluetooth(): send message to clients");
281                         send_to_clients();
282                         if (clients.isEmpty()) {
283                                 if (D) Log.d(TAG, "stop_altos_bluetooth(): no clients, terminating");
284                                 stopSelf();
285                         }
286                 }
287         }
288
289         private void start_altos_bluetooth(DeviceAddress address) {
290                 // Get the BLuetoothDevice object
291                 BluetoothDevice device = bluetooth_adapter.getRemoteDevice(address.address);
292
293                 stop_altos_bluetooth(false);
294                 this.address = address;
295                 if (D) Log.d(TAG, String.format("start_altos_bluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress()));
296                 altos_bluetooth = new AltosBluetooth(device, handler);
297                 telemetry_state.connect = TelemetryState.CONNECT_CONNECTING;
298                 telemetry_state.address = address;
299                 send_to_clients();
300         }
301
302         private void connected() throws InterruptedException {
303                 if (D) Log.d(TAG, "connected top");
304                 try {
305                         if (altos_bluetooth == null)
306                                 throw new InterruptedException("no bluetooth");
307                         telemetry_state.config = altos_bluetooth.config_data();
308                         altos_bluetooth.set_radio_frequency(telemetry_state.frequency);
309                         altos_bluetooth.set_telemetry_rate(telemetry_state.telemetry_rate);
310                 } catch (TimeoutException e) {
311                         // If this timed out, then we really want to retry it, but
312                         // probably safer to just retry the connection from scratch.
313                         handler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
314                         return;
315                 }
316
317                 if (D) Log.d(TAG, "connected bluetooth configured");
318                 telemetry_state.connect = TelemetryState.CONNECT_CONNECTED;
319                 telemetry_state.address = address;
320
321                 telemetry_reader = new TelemetryReader(altos_bluetooth, handler, telemetry_state.state);
322                 telemetry_reader.start();
323
324                 if (D) Log.d(TAG, "connected TelemetryReader started");
325
326                 telemetry_logger = new TelemetryLogger(this, altos_bluetooth);
327
328                 if (D) Log.d(TAG, "Notify UI of connection");
329
330                 send_to_clients();
331         }
332
333
334         @Override
335         public void onCreate() {
336                 // Get local Bluetooth adapter
337                 bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
338
339                 // If the adapter is null, then Bluetooth is not supported
340                 if (bluetooth_adapter == null) {
341                         Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
342                 }
343
344                 // Initialise preferences
345                 AltosDroidPreferences.init(this);
346
347                 telemetry_state = new TelemetryState();
348
349                 // Create a reference to the NotificationManager so that we can update our notifcation text later
350                 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
351
352                 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
353                 telemetry_state.address = null;
354
355                 AltosSavedState saved_state = AltosPreferences.state(0);
356
357                 if (saved_state != null) {
358                         if (D) Log.d(TAG, String.format("recovered old state flight %d\n", saved_state.state.flight));
359                         telemetry_state.state = saved_state.state;
360                 }
361
362                 // Listen for GPS and Network position updates
363                 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
364
365                 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
366
367                 DeviceAddress address = AltosDroidPreferences.active_device();
368                 if (address != null)
369                         start_altos_bluetooth(address);
370         }
371
372         @Override
373         public int onStartCommand(Intent intent, int flags, int startId) {
374                 Log.i("TelemetryService", "Received start id " + startId + ": " + intent);
375
376                 CharSequence text = getText(R.string.telemetry_service_started);
377
378                 // Create notification to be displayed while the service runs
379                 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
380
381                 // The PendingIntent to launch our activity if the user selects this notification
382                 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
383                                 new Intent(this, AltosDroid.class), 0);
384
385                 // Set the info for the views that show in the notification panel.
386                 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
387
388                 // Set the notification to be in the "Ongoing" section.
389                 notification.flags |= Notification.FLAG_ONGOING_EVENT;
390
391                 // Move us into the foreground.
392                 startForeground(NOTIFICATION, notification);
393
394                 // We want this service to continue running until it is explicitly
395                 // stopped, so return sticky.
396                 return START_STICKY;
397         }
398
399         @Override
400         public void onDestroy() {
401
402                 // Stop listening for location updates
403                 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
404
405                 // Stop the bluetooth Comms threads
406                 stop_altos_bluetooth(true);
407
408                 // Demote us from the foreground, and cancel the persistent notification.
409                 stopForeground(true);
410
411                 // Tell the user we stopped.
412                 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
413         }
414
415         @Override
416         public IBinder onBind(Intent intent) {
417                 return messenger.getBinder();
418         }
419
420
421         public void onLocationChanged(Location location) {
422                 telemetry_state.location = location;
423                 if (D) Log.d(TAG, "location changed");
424                 send_to_clients();
425         }
426
427         public void onStatusChanged(String provider, int status, Bundle extras) {
428         }
429
430         public void onProviderEnabled(String provider) {
431         }
432
433         public void onProviderDisabled(String provider) {
434         }
435
436 }