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