altosdroid: Switch to NotificationCompat
[fw/altos] / altosdroid / app / src / main / java / 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; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
17  */
18
19 package org.altusmetrum.AltosDroid;
20
21 import java.lang.ref.WeakReference;
22 import java.util.concurrent.TimeoutException;
23 import java.util.*;
24
25 import android.app.*;
26 import android.bluetooth.BluetoothDevice;
27 import android.bluetooth.BluetoothAdapter;
28 import android.graphics.Color;
29 import android.hardware.usb.*;
30 import android.content.Intent;
31 import android.content.Context;
32 import android.os.*;
33 import android.widget.Toast;
34 import androidx.core.app.NotificationCompat;
35
36 import org.altusmetrum.altoslib_13.*;
37
38 public class TelemetryService extends Service implements AltosIdleMonitorListener {
39
40         static final int MSG_REGISTER_CLIENT   = 1;
41         static final int MSG_UNREGISTER_CLIENT = 2;
42         static final int MSG_CONNECT           = 3;
43         static final int MSG_OPEN_USB          = 4;
44         static final int MSG_CONNECTED         = 5;
45         static final int MSG_CONNECT_FAILED    = 6;
46         static final int MSG_DISCONNECTED      = 7;
47         static final int MSG_TELEMETRY         = 8;
48         static final int MSG_SETFREQUENCY      = 9;
49         static final int MSG_CRC_ERROR         = 10;
50         static final int MSG_SETBAUD           = 11;
51         static final int MSG_DISCONNECT        = 12;
52         static final int MSG_DELETE_SERIAL     = 13;
53         static final int MSG_BLUETOOTH_ENABLED = 14;
54         static final int MSG_MONITOR_IDLE_START= 15;
55         static final int MSG_MONITOR_IDLE_STOP = 16;
56         static final int MSG_REBOOT            = 17;
57         static final int MSG_IGNITER_QUERY     = 18;
58         static final int MSG_IGNITER_FIRE      = 19;
59
60         // Unique Identification Number for the Notification.
61         // We use it on Notification start, and to cancel it.
62         private int NOTIFICATION = R.string.telemetry_service_label;
63         //private NotificationManager mNM;
64
65         ArrayList<Messenger> clients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
66         final Handler   handler   = new IncomingHandler(this);
67         final Messenger messenger = new Messenger(handler); // Target we publish for clients to send messages to IncomingHandler.
68
69         // Name of the connected device
70         DeviceAddress address;
71         private AltosDroidLink  altos_link  = null;
72         private TelemetryReader telemetry_reader = null;
73         private TelemetryLogger telemetry_logger = null;
74
75         // Local Bluetooth adapter
76         private BluetoothAdapter bluetooth_adapter = null;
77
78         // Last data seen; send to UI when it starts
79         private TelemetryState  telemetry_state;
80
81         // Idle monitor if active
82         AltosIdleMonitor idle_monitor = null;
83
84         // Igniter bits
85         AltosIgnite ignite = null;
86         boolean ignite_running;
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                         DeviceAddress address;
96
97                         TelemetryService s = service.get();
98                         AltosDroidLink bt = null;
99                         if (s == null)
100                                 return;
101
102                         switch (msg.what) {
103
104                                 /* Messages from application */
105                         case MSG_REGISTER_CLIENT:
106                                 s.add_client(msg.replyTo);
107                                 break;
108                         case MSG_UNREGISTER_CLIENT:
109                                 s.remove_client(msg.replyTo);
110                                 break;
111                         case MSG_CONNECT:
112                                 AltosDebug.debug("Connect command received");
113                                 address = (DeviceAddress) msg.obj;
114                                 AltosDroidPreferences.set_active_device(address);
115                                 s.start_altos_bluetooth(address, false);
116                                 break;
117                         case MSG_OPEN_USB:
118                                 AltosDebug.debug("Open USB command received");
119                                 UsbDevice device = (UsbDevice) msg.obj;
120                                 s.start_usb(device);
121                                 break;
122                         case MSG_DISCONNECT:
123                                 AltosDebug.debug("Disconnect command received");
124                                 s.address = null;
125                                 if (!(Boolean) msg.obj)
126                                         AltosDroidPreferences.set_active_device(null);
127                                 s.disconnect(true);
128                                 break;
129                         case MSG_DELETE_SERIAL:
130                                 AltosDebug.debug("Delete Serial command received");
131                                 s.delete_serial((Integer) msg.obj);
132                                 break;
133                         case MSG_SETFREQUENCY:
134                                 AltosDebug.debug("MSG_SETFREQUENCY");
135                                 s.telemetry_state.frequency = (Double) msg.obj;
136                                 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
137                                         try {
138                                                 s.altos_link.set_radio_frequency(s.telemetry_state.frequency);
139                                                 s.altos_link.save_frequency();
140                                         } catch (InterruptedException e) {
141                                         } catch (TimeoutException e) {
142                                         }
143                                 }
144                                 s.send_to_clients();
145                                 break;
146                         case MSG_SETBAUD:
147                                 AltosDebug.debug("MSG_SETBAUD");
148                                 s.telemetry_state.telemetry_rate = (Integer) msg.obj;
149                                 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
150                                         s.altos_link.set_telemetry_rate(s.telemetry_state.telemetry_rate);
151                                         s.altos_link.save_telemetry_rate();
152                                 }
153                                 s.send_to_clients();
154                                 break;
155
156                                 /*
157                                  *Messages from AltosBluetooth
158                                  */
159                         case MSG_CONNECTED:
160                                 AltosDebug.debug("MSG_CONNECTED");
161                                 bt = (AltosDroidLink) msg.obj;
162
163                                 if (bt != s.altos_link) {
164                                         AltosDebug.debug("Stale message");
165                                         break;
166                                 }
167                                 AltosDebug.debug("Connected to device");
168                                 try {
169                                         s.connected();
170                                 } catch (InterruptedException ie) {
171                                 }
172                                 break;
173                         case MSG_CONNECT_FAILED:
174                                 AltosDebug.debug("MSG_CONNECT_FAILED");
175                                 bt = (AltosDroidLink) msg.obj;
176
177                                 if (bt != s.altos_link) {
178                                         AltosDebug.debug("Stale message");
179                                         break;
180                                 }
181                                 if (s.address != null) {
182                                         AltosDebug.debug("Connection failed... retrying");
183                                         s.start_altos_bluetooth(s.address, true);
184                                 } else {
185                                         s.disconnect(true);
186                                 }
187                                 break;
188                         case MSG_DISCONNECTED:
189
190                                 /* This can be sent by either AltosDroidLink or TelemetryReader */
191                                 AltosDebug.debug("MSG_DISCONNECTED");
192                                 bt = (AltosDroidLink) msg.obj;
193
194                                 if (bt != s.altos_link) {
195                                         AltosDebug.debug("Stale message");
196                                         break;
197                                 }
198                                 if (s.address != null) {
199                                         AltosDebug.debug("Connection lost... retrying");
200                                         s.start_altos_bluetooth(s.address, true);
201                                 } else {
202                                         s.disconnect(true);
203                                 }
204                                 break;
205
206                                 /*
207                                  * Messages from TelemetryReader
208                                  */
209                         case MSG_TELEMETRY:
210                                 s.telemetry((AltosTelemetry) msg.obj);
211                                 break;
212                         case MSG_CRC_ERROR:
213                                 // forward crc error messages
214                                 s.telemetry_state.crc_errors = (Integer) msg.obj;
215                                 s.send_to_clients();
216                                 break;
217                         case MSG_BLUETOOTH_ENABLED:
218                                 AltosDebug.debug("TelemetryService notes that BT is now enabled");
219                                 address = AltosDroidPreferences.active_device();
220                                 if (address != null && !address.address.startsWith("USB"))
221                                         s.start_altos_bluetooth(address, false);
222                                 break;
223                         case MSG_MONITOR_IDLE_START:
224                                 AltosDebug.debug("start monitor idle");
225                                 s.start_idle_monitor();
226                                 break;
227                         case MSG_MONITOR_IDLE_STOP:
228                                 AltosDebug.debug("stop monitor idle");
229                                 s.stop_idle_monitor();
230                                 break;
231                         case MSG_REBOOT:
232                                 AltosDebug.debug("reboot");
233                                 s.reboot_remote();
234                                 break;
235                         case MSG_IGNITER_QUERY:
236                                 AltosDebug.debug("igniter query");
237                                 s.igniter_query(msg.replyTo);
238                                 break;
239                         case MSG_IGNITER_FIRE:
240                                 AltosDebug.debug("igniter fire");
241                                 s.igniter_fire((String) msg.obj);
242                                 break;
243                         default:
244                                 super.handleMessage(msg);
245                         }
246                 }
247         }
248
249         /* Handle telemetry packet
250          */
251         private void telemetry(AltosTelemetry telem) {
252                 AltosState      state;
253
254                 if (telemetry_state.states.containsKey(telem.serial()))
255                         state = telemetry_state.states.get(telem.serial());
256                 else
257                         state = new AltosState(new AltosCalData());
258                 telem.provide_data(state);
259                 telemetry_state.states.put(telem.serial(), state);
260                 telemetry_state.quiet = false;
261                 if (state != null) {
262                         AltosPreferences.set_state(state,telem.serial());
263                 }
264                 send_to_clients();
265         }
266
267         /* Construct the message to deliver to clients
268          */
269         private Message message() {
270                 if (telemetry_state == null)
271                         AltosDebug.debug("telemetry_state null!");
272                 if (telemetry_state.states == null)
273                         AltosDebug.debug("telemetry_state.states null!");
274                 return Message.obtain(null, AltosDroid.MSG_STATE, telemetry_state);
275         }
276
277         /* A new friend has connected
278          */
279         private void add_client(Messenger client) {
280
281                 clients.add(client);
282                 AltosDebug.debug("Client bound to service");
283
284                 /* On connect, send the current state to the new client
285                  */
286                 send_to_client(client);
287                 send_idle_mode_to_client(client);
288
289                 /* If we've got an address from a previous session, then
290                  * go ahead and try to reconnect to the device
291                  */
292                 if (address != null && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
293                         AltosDebug.debug("Reconnecting now...");
294                         start_altos_bluetooth(address, false);
295                 }
296         }
297
298         /* A client has disconnected, clean up
299          */
300         private void remove_client(Messenger client) {
301                 clients.remove(client);
302                 AltosDebug.debug("Client unbound from service");
303
304                 /* When the list of clients is empty, stop the service if
305                  * we have no current telemetry source
306                  */
307
308                  if (clients.isEmpty() && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
309                          AltosDebug.debug("No clients, no connection. Stopping\n");
310                          stopSelf();
311                  }
312         }
313
314         private void send_to_client(Messenger client) {
315                 Message m = message();
316                 try {
317                         client.send(m);
318                 } catch (RemoteException e) {
319                         AltosDebug.error("Client %s disappeared", client.toString());
320                         remove_client(client);
321                 }
322         }
323
324         private void send_to_clients() {
325                 for (Messenger client : clients)
326                         send_to_client(client);
327         }
328
329         private void send_idle_mode_to_client(Messenger client) {
330                 Message m = Message.obtain(null, AltosDroid.MSG_IDLE_MODE, idle_monitor != null);
331                 try {
332                         client.send(m);
333                 } catch (RemoteException e) {
334                         AltosDebug.error("Client %s disappeared", client.toString());
335                         remove_client(client);
336                 }
337         }
338
339         private void send_idle_mode_to_clients() {
340                 for (Messenger client : clients)
341                         send_idle_mode_to_client(client);
342         }
343
344         private void telemetry_start() {
345                 if (telemetry_reader == null && idle_monitor == null && !ignite_running) {
346                         telemetry_reader = new TelemetryReader(altos_link, handler);
347                         telemetry_reader.start();
348                 }
349         }
350
351         private void telemetry_stop() {
352                 if (telemetry_reader != null) {
353                         AltosDebug.debug("disconnect(): stopping TelemetryReader");
354                         telemetry_reader.interrupt();
355                         try {
356                                 telemetry_reader.join();
357                         } catch (InterruptedException e) {
358                         }
359                         telemetry_reader = null;
360                 }
361         }
362
363         private void disconnect(boolean notify) {
364                 AltosDebug.debug("disconnect(): begin");
365
366                 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
367                 telemetry_state.address = null;
368
369                 if (idle_monitor != null)
370                         stop_idle_monitor();
371
372                 if (altos_link != null)
373                         altos_link.closing();
374
375                 stop_receiver_voltage_timer();
376
377                 telemetry_stop();
378                 if (telemetry_logger != null) {
379                         AltosDebug.debug("disconnect(): stopping TelemetryLogger");
380                         telemetry_logger.stop();
381                         telemetry_logger = null;
382                 }
383                 if (altos_link != null) {
384                         AltosDebug.debug("disconnect(): stopping AltosDroidLink");
385                         altos_link.close();
386                         altos_link = null;
387                         ignite = null;
388                 }
389                 telemetry_state.config = null;
390                 if (notify) {
391                         AltosDebug.debug("disconnect(): send message to clients");
392                         send_to_clients();
393                         if (clients.isEmpty()) {
394                                 AltosDebug.debug("disconnect(): no clients, terminating");
395                                 stopSelf();
396                         }
397                 }
398         }
399
400         private void start_usb(UsbDevice device) {
401                 AltosUsb        d = new AltosUsb(this, device, handler);
402
403                 if (d != null) {
404                         disconnect(false);
405                         altos_link = d;
406                         try {
407                                 connected();
408                         } catch (InterruptedException ie) {
409                         }
410                 }
411         }
412
413         private void delete_serial(int serial) {
414                 telemetry_state.states.remove((Integer) serial);
415                 AltosPreferences.remove_state(serial);
416                 send_to_clients();
417         }
418
419         private void start_altos_bluetooth(DeviceAddress address, boolean pause) {
420                 if (bluetooth_adapter == null || !bluetooth_adapter.isEnabled())
421                         return;
422
423                 disconnect(false);
424
425                 // Get the BluetoothDevice object
426                 BluetoothDevice device = bluetooth_adapter.getRemoteDevice(address.address);
427
428                 this.address = address;
429                 AltosDebug.debug("start_altos_bluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress());
430                 altos_link = new AltosBluetooth(device, handler, pause);
431                 telemetry_state.connect = TelemetryState.CONNECT_CONNECTING;
432                 telemetry_state.address = address;
433                 send_to_clients();
434         }
435
436         private void start_idle_monitor() {
437                 if (altos_link != null && idle_monitor == null) {
438                         telemetry_stop();
439                         idle_monitor = new AltosIdleMonitor(this, altos_link, true, false);
440                         idle_monitor.set_callsign(AltosPreferences.callsign());
441                         idle_monitor.start();
442                         send_idle_mode_to_clients();
443                 }
444         }
445
446         private void stop_idle_monitor() {
447                 if (idle_monitor != null) {
448                         try {
449                                 idle_monitor.abort();
450                         } catch (InterruptedException ie) {
451                         }
452                         idle_monitor = null;
453                         telemetry_start();
454                         send_idle_mode_to_clients();
455                 }
456         }
457
458         private void reboot_remote() {
459                 if (altos_link != null) {
460                         stop_idle_monitor();
461                         try {
462                                 altos_link.start_remote();
463                                 altos_link.printf("r eboot\n");
464                                 altos_link.flush_output();
465                         } catch (TimeoutException te) {
466                         } catch (InterruptedException ie) {
467                         } finally {
468                                 try {
469                                         altos_link.stop_remote();
470                                 } catch (InterruptedException ie) {
471                                 }
472                         }
473                 }
474         }
475
476         private void ensure_ignite() {
477                 if (ignite == null)
478                         ignite = new AltosIgnite(altos_link, true, false);
479         }
480
481         private synchronized void igniter_query(Messenger client) {
482                 ensure_ignite();
483                 HashMap<String,Integer> status_map = null;
484                 ignite_running = true;
485                 try {
486                         stop_idle_monitor();
487                         try {
488                                 status_map = ignite.status();
489                         } catch (InterruptedException ie) {
490                                 AltosDebug.debug("ignite.status interrupted");
491                         } catch (TimeoutException te) {
492                                 AltosDebug.debug("ignite.status timeout");
493                         }
494                 } finally {
495                         ignite_running = false;
496                 }
497                 Message m = Message.obtain(null, AltosDroid.MSG_IGNITER_STATUS, status_map);
498                 try {
499                         client.send(m);
500                 } catch (RemoteException e) {
501                 }
502         }
503
504         private synchronized void igniter_fire(String igniter) {
505                 ensure_ignite();
506                 ignite_running = true;
507                 stop_idle_monitor();
508                 try {
509                         ignite.fire(igniter);
510                 } catch (InterruptedException ie) {
511                 } finally {
512                         ignite_running = false;
513                 }
514         }
515
516         // Timer for receiver battery voltage monitoring
517         Timer receiver_voltage_timer;
518
519         private void update_receiver_voltage() {
520                 if (altos_link != null && idle_monitor == null && !ignite_running) {
521                         try {
522                                 double  voltage = altos_link.monitor_battery();
523                                 telemetry_state.receiver_battery = voltage;
524                                 send_to_clients();
525                         } catch (InterruptedException ie) {
526                         }
527                 }
528         }
529
530         private void stop_receiver_voltage_timer() {
531                 if (receiver_voltage_timer != null) {
532                         receiver_voltage_timer.cancel();
533                         receiver_voltage_timer.purge();
534                         receiver_voltage_timer = null;
535                 }
536         }
537
538         private void start_receiver_voltage_timer() {
539                 if (receiver_voltage_timer == null && altos_link.has_monitor_battery()) {
540                         receiver_voltage_timer = new Timer();
541                         receiver_voltage_timer.scheduleAtFixedRate(new TimerTask() { public void run() {update_receiver_voltage();}}, 1000L, 10000L);
542                 }
543         }
544
545         private void connected() throws InterruptedException {
546                 AltosDebug.debug("connected top");
547                 AltosDebug.check_ui("connected\n");
548                 try {
549                         if (altos_link == null)
550                                 throw new InterruptedException("no bluetooth");
551                         telemetry_state.config = altos_link.config_data();
552                         altos_link.set_radio_frequency(telemetry_state.frequency);
553                         altos_link.set_telemetry_rate(telemetry_state.telemetry_rate);
554                 } catch (TimeoutException e) {
555                         // If this timed out, then we really want to retry it, but
556                         // probably safer to just retry the connection from scratch.
557                         AltosDebug.debug("connected timeout");
558                         if (address != null) {
559                                 AltosDebug.debug("connected timeout, retrying");
560                                 start_altos_bluetooth(address, true);
561                         } else {
562                                 handler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
563                                 disconnect(true);
564                         }
565                         return;
566                 }
567
568                 AltosDebug.debug("connected bluetooth configured");
569                 telemetry_state.connect = TelemetryState.CONNECT_CONNECTED;
570                 telemetry_state.address = address;
571
572                 telemetry_start();
573
574                 AltosDebug.debug("connected TelemetryReader started");
575
576                 telemetry_logger = new TelemetryLogger(this, altos_link);
577
578                 start_receiver_voltage_timer();
579
580                 AltosDebug.debug("Notify UI of connection");
581
582                 send_to_clients();
583         }
584
585
586         @Override
587         public void onCreate() {
588
589                 AltosDebug.init(this);
590
591                 // Initialise preferences
592                 AltosDroidPreferences.init(this);
593
594                 // Get local Bluetooth adapter
595                 bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
596
597                 telemetry_state = new TelemetryState();
598
599                 // Create a reference to the NotificationManager so that we can update our notifcation text later
600                 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
601
602                 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
603                 telemetry_state.address = null;
604
605                 /* Pull the saved state information out of the preferences database
606                  */
607                 ArrayList<Integer> serials = AltosPreferences.list_states();
608
609                 telemetry_state.latest_serial = AltosPreferences.latest_state();
610
611                 telemetry_state.quiet = true;
612
613                 AltosDebug.debug("latest serial %d\n", telemetry_state.latest_serial);
614
615                 for (int serial : serials) {
616                         AltosState saved_state = AltosPreferences.state(serial);
617                         if (saved_state != null) {
618                                 if (telemetry_state.latest_serial == 0)
619                                         telemetry_state.latest_serial = serial;
620
621                                 AltosDebug.debug("recovered old state serial %d flight %d",
622                                                  serial,
623                                                  saved_state.cal_data().flight);
624                                 if (saved_state.gps != null)
625                                         AltosDebug.debug("\tposition %f,%f",
626                                                          saved_state.gps.lat,
627                                                          saved_state.gps.lon);
628                                 telemetry_state.states.put(serial, saved_state);
629                         } else {
630                                 AltosDebug.debug("Failed to recover state for %d", serial);
631                                 AltosPreferences.remove_state(serial);
632                         }
633                 }
634         }
635
636
637         private String createNotificationChannel(String channelId, String channelName) {
638                 NotificationChannel chan = new NotificationChannel(
639                                 channelId, channelName, NotificationManager.IMPORTANCE_NONE);
640                 chan.setLightColor(Color.BLUE);
641                 chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
642                 NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
643                 service.createNotificationChannel(chan);
644                 return channelId;
645         }
646
647         @Override
648         public int onStartCommand(Intent intent, int flags, int startId) {
649                 AltosDebug.debug("Received start id %d: %s", startId, intent);
650
651                 // The PendingIntent to launch our activity if the user selects this notification
652                 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
653                                 new Intent(this, AltosDroid.class), 0);
654
655                 String channelId =
656                                 (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
657                                                 ? createNotificationChannel("altosdroid_telemetry", "AltosDroid Telemetry Service")
658                                                 : "";
659
660                 // Create notification to be displayed while the service runs
661                 Notification notification = new NotificationCompat.Builder(this, channelId)
662                                 .setContentTitle(getText(R.string.telemetry_service_label))
663                                 .setContentText(getText(R.string.telemetry_service_started))
664                                 .setContentIntent(contentIntent)
665                                 .setWhen(System.currentTimeMillis())
666                                 .setOngoing(true)
667                                 .setSmallIcon(R.drawable.am_status_c)
668 //                              .setLargeIcon(R.drawable.am_status_c)
669                                 .build();
670
671                 // Move us into the foreground.
672                 startForeground(NOTIFICATION, notification);
673
674                 /* Start bluetooth if we don't have a connection already */
675                 if (intent != null &&
676                     (telemetry_state.connect == TelemetryState.CONNECT_NONE ||
677                      telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED))
678                 {
679                         String  action = intent.getAction();
680
681                         if (action.equals(AltosDroid.ACTION_BLUETOOTH)) {
682                                 DeviceAddress address = AltosDroidPreferences.active_device();
683                                 if (address != null && !address.address.startsWith("USB"))
684                                         start_altos_bluetooth(address, false);
685                         }
686                 }
687
688                 // We want this service to continue running until it is explicitly
689                 // stopped, so return sticky.
690                 return START_STICKY;
691         }
692
693         @Override
694         public void onDestroy() {
695
696                 // Stop the bluetooth Comms threads
697                 disconnect(true);
698
699                 // Demote us from the foreground, and cancel the persistent notification.
700                 stopForeground(true);
701
702                 // Tell the user we stopped.
703                 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
704         }
705
706         @Override
707         public IBinder onBind(Intent intent) {
708                 return messenger.getBinder();
709         }
710
711         /* AltosIdleMonitorListener */
712         public void update(AltosState state, AltosListenerState listener_state) {
713                 telemetry_state.states.put(state.cal_data().serial, state);
714                 telemetry_state.receiver_battery = listener_state.battery;
715                 send_to_clients();
716         }
717
718         public void failed() {
719         }
720
721         public void error(String reason) {
722                 stop_idle_monitor();
723         }
724 }