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