Update persistent notification in TelemetryService
[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
35 import org.altusmetrum.altoslib_13.*;
36
37 public class TelemetryService extends Service implements AltosIdleMonitorListener {
38
39         static final int MSG_REGISTER_CLIENT   = 1;
40         static final int MSG_UNREGISTER_CLIENT = 2;
41         static final int MSG_CONNECT           = 3;
42         static final int MSG_OPEN_USB          = 4;
43         static final int MSG_CONNECTED         = 5;
44         static final int MSG_CONNECT_FAILED    = 6;
45         static final int MSG_DISCONNECTED      = 7;
46         static final int MSG_TELEMETRY         = 8;
47         static final int MSG_SETFREQUENCY      = 9;
48         static final int MSG_CRC_ERROR         = 10;
49         static final int MSG_SETBAUD           = 11;
50         static final int MSG_DISCONNECT        = 12;
51         static final int MSG_DELETE_SERIAL     = 13;
52         static final int MSG_BLUETOOTH_ENABLED = 14;
53         static final int MSG_MONITOR_IDLE_START= 15;
54         static final int MSG_MONITOR_IDLE_STOP = 16;
55         static final int MSG_REBOOT            = 17;
56         static final int MSG_IGNITER_QUERY     = 18;
57         static final int MSG_IGNITER_FIRE      = 19;
58
59         // Unique Identification Number for the Notification.
60         // We use it on Notification start, and to cancel it.
61         private int NOTIFICATION = R.string.telemetry_service_label;
62         //private NotificationManager mNM;
63
64         ArrayList<Messenger> clients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
65         final Handler   handler   = new IncomingHandler(this);
66         final Messenger messenger = new Messenger(handler); // Target we publish for clients to send messages to IncomingHandler.
67
68         // Name of the connected device
69         DeviceAddress address;
70         private AltosDroidLink  altos_link  = null;
71         private TelemetryReader telemetry_reader = null;
72         private TelemetryLogger telemetry_logger = null;
73
74         // Local Bluetooth adapter
75         private BluetoothAdapter bluetooth_adapter = null;
76
77         // Last data seen; send to UI when it starts
78         private TelemetryState  telemetry_state;
79
80         // Idle monitor if active
81         AltosIdleMonitor idle_monitor = null;
82
83         // Igniter bits
84         AltosIgnite ignite = null;
85         boolean ignite_running;
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                         DeviceAddress address;
95
96                         TelemetryService s = service.get();
97                         AltosDroidLink bt = null;
98                         if (s == null)
99                                 return;
100
101                         switch (msg.what) {
102
103                                 /* Messages from application */
104                         case MSG_REGISTER_CLIENT:
105                                 s.add_client(msg.replyTo);
106                                 break;
107                         case MSG_UNREGISTER_CLIENT:
108                                 s.remove_client(msg.replyTo);
109                                 break;
110                         case MSG_CONNECT:
111                                 AltosDebug.debug("Connect command received");
112                                 address = (DeviceAddress) msg.obj;
113                                 AltosDroidPreferences.set_active_device(address);
114                                 s.start_altos_bluetooth(address, false);
115                                 break;
116                         case MSG_OPEN_USB:
117                                 AltosDebug.debug("Open USB command received");
118                                 UsbDevice device = (UsbDevice) msg.obj;
119                                 s.start_usb(device);
120                                 break;
121                         case MSG_DISCONNECT:
122                                 AltosDebug.debug("Disconnect command received");
123                                 s.address = null;
124                                 if (!(Boolean) msg.obj)
125                                         AltosDroidPreferences.set_active_device(null);
126                                 s.disconnect(true);
127                                 break;
128                         case MSG_DELETE_SERIAL:
129                                 AltosDebug.debug("Delete Serial command received");
130                                 s.delete_serial((Integer) msg.obj);
131                                 break;
132                         case MSG_SETFREQUENCY:
133                                 AltosDebug.debug("MSG_SETFREQUENCY");
134                                 s.telemetry_state.frequency = (Double) msg.obj;
135                                 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
136                                         try {
137                                                 s.altos_link.set_radio_frequency(s.telemetry_state.frequency);
138                                                 s.altos_link.save_frequency();
139                                         } catch (InterruptedException e) {
140                                         } catch (TimeoutException e) {
141                                         }
142                                 }
143                                 s.send_to_clients();
144                                 break;
145                         case MSG_SETBAUD:
146                                 AltosDebug.debug("MSG_SETBAUD");
147                                 s.telemetry_state.telemetry_rate = (Integer) msg.obj;
148                                 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
149                                         s.altos_link.set_telemetry_rate(s.telemetry_state.telemetry_rate);
150                                         s.altos_link.save_telemetry_rate();
151                                 }
152                                 s.send_to_clients();
153                                 break;
154
155                                 /*
156                                  *Messages from AltosBluetooth
157                                  */
158                         case MSG_CONNECTED:
159                                 AltosDebug.debug("MSG_CONNECTED");
160                                 bt = (AltosDroidLink) msg.obj;
161
162                                 if (bt != s.altos_link) {
163                                         AltosDebug.debug("Stale message");
164                                         break;
165                                 }
166                                 AltosDebug.debug("Connected to device");
167                                 try {
168                                         s.connected();
169                                 } catch (InterruptedException ie) {
170                                 }
171                                 break;
172                         case MSG_CONNECT_FAILED:
173                                 AltosDebug.debug("MSG_CONNECT_FAILED");
174                                 bt = (AltosDroidLink) msg.obj;
175
176                                 if (bt != s.altos_link) {
177                                         AltosDebug.debug("Stale message");
178                                         break;
179                                 }
180                                 if (s.address != null) {
181                                         AltosDebug.debug("Connection failed... retrying");
182                                         s.start_altos_bluetooth(s.address, true);
183                                 } else {
184                                         s.disconnect(true);
185                                 }
186                                 break;
187                         case MSG_DISCONNECTED:
188
189                                 /* This can be sent by either AltosDroidLink or TelemetryReader */
190                                 AltosDebug.debug("MSG_DISCONNECTED");
191                                 bt = (AltosDroidLink) msg.obj;
192
193                                 if (bt != s.altos_link) {
194                                         AltosDebug.debug("Stale message");
195                                         break;
196                                 }
197                                 if (s.address != null) {
198                                         AltosDebug.debug("Connection lost... retrying");
199                                         s.start_altos_bluetooth(s.address, true);
200                                 } else {
201                                         s.disconnect(true);
202                                 }
203                                 break;
204
205                                 /*
206                                  * Messages from TelemetryReader
207                                  */
208                         case MSG_TELEMETRY:
209                                 s.telemetry((AltosTelemetry) msg.obj);
210                                 break;
211                         case MSG_CRC_ERROR:
212                                 // forward crc error messages
213                                 s.telemetry_state.crc_errors = (Integer) msg.obj;
214                                 s.send_to_clients();
215                                 break;
216                         case MSG_BLUETOOTH_ENABLED:
217                                 AltosDebug.debug("TelemetryService notes that BT is now enabled");
218                                 address = AltosDroidPreferences.active_device();
219                                 if (address != null && !address.address.startsWith("USB"))
220                                         s.start_altos_bluetooth(address, false);
221                                 break;
222                         case MSG_MONITOR_IDLE_START:
223                                 AltosDebug.debug("start monitor idle");
224                                 s.start_idle_monitor();
225                                 break;
226                         case MSG_MONITOR_IDLE_STOP:
227                                 AltosDebug.debug("stop monitor idle");
228                                 s.stop_idle_monitor();
229                                 break;
230                         case MSG_REBOOT:
231                                 AltosDebug.debug("reboot");
232                                 s.reboot_remote();
233                                 break;
234                         case MSG_IGNITER_QUERY:
235                                 AltosDebug.debug("igniter query");
236                                 s.igniter_query(msg.replyTo);
237                                 break;
238                         case MSG_IGNITER_FIRE:
239                                 AltosDebug.debug("igniter fire");
240                                 s.igniter_fire((String) msg.obj);
241                                 break;
242                         default:
243                                 super.handleMessage(msg);
244                         }
245                 }
246         }
247
248         /* Handle telemetry packet
249          */
250         private void telemetry(AltosTelemetry telem) {
251                 AltosState      state;
252
253                 if (telemetry_state.states.containsKey(telem.serial()))
254                         state = telemetry_state.states.get(telem.serial());
255                 else
256                         state = new AltosState(new AltosCalData());
257                 telem.provide_data(state);
258                 telemetry_state.states.put(telem.serial(), state);
259                 telemetry_state.quiet = false;
260                 if (state != null) {
261                         AltosPreferences.set_state(state,telem.serial());
262                 }
263                 send_to_clients();
264         }
265
266         /* Construct the message to deliver to clients
267          */
268         private Message message() {
269                 if (telemetry_state == null)
270                         AltosDebug.debug("telemetry_state null!");
271                 if (telemetry_state.states == null)
272                         AltosDebug.debug("telemetry_state.states 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.states.remove((Integer) 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.start();
441                         send_idle_mode_to_clients();
442                 }
443         }
444
445         private void stop_idle_monitor() {
446                 if (idle_monitor != null) {
447                         try {
448                                 idle_monitor.abort();
449                         } catch (InterruptedException ie) {
450                         }
451                         idle_monitor = null;
452                         telemetry_start();
453                         send_idle_mode_to_clients();
454                 }
455         }
456
457         private void reboot_remote() {
458                 if (altos_link != null) {
459                         stop_idle_monitor();
460                         try {
461                                 altos_link.start_remote();
462                                 altos_link.printf("r eboot\n");
463                                 altos_link.flush_output();
464                         } catch (TimeoutException te) {
465                         } catch (InterruptedException ie) {
466                         } finally {
467                                 try {
468                                         altos_link.stop_remote();
469                                 } catch (InterruptedException ie) {
470                                 }
471                         }
472                 }
473         }
474
475         private void ensure_ignite() {
476                 if (ignite == null)
477                         ignite = new AltosIgnite(altos_link, true, false);
478         }
479
480         private synchronized void igniter_query(Messenger client) {
481                 ensure_ignite();
482                 HashMap<String,Integer> status_map = null;
483                 ignite_running = true;
484                 try {
485                         stop_idle_monitor();
486                         try {
487                                 status_map = ignite.status();
488                         } catch (InterruptedException ie) {
489                                 AltosDebug.debug("ignite.status interrupted");
490                         } catch (TimeoutException te) {
491                                 AltosDebug.debug("ignite.status timeout");
492                         }
493                 } finally {
494                         ignite_running = false;
495                 }
496                 Message m = Message.obtain(null, AltosDroid.MSG_IGNITER_STATUS, status_map);
497                 try {
498                         client.send(m);
499                 } catch (RemoteException e) {
500                 }
501         }
502
503         private synchronized void igniter_fire(String igniter) {
504                 ensure_ignite();
505                 ignite_running = true;
506                 stop_idle_monitor();
507                 try {
508                         ignite.fire(igniter);
509                 } catch (InterruptedException ie) {
510                 } finally {
511                         ignite_running = false;
512                 }
513         }
514
515         // Timer for receiver battery voltage monitoring
516         Timer receiver_voltage_timer;
517
518         private void update_receiver_voltage() {
519                 if (altos_link != null && idle_monitor == null && !ignite_running) {
520                         try {
521                                 double  voltage = altos_link.monitor_battery();
522                                 telemetry_state.receiver_battery = voltage;
523                                 send_to_clients();
524                         } catch (InterruptedException ie) {
525                         }
526                 }
527         }
528
529         private void stop_receiver_voltage_timer() {
530                 if (receiver_voltage_timer != null) {
531                         receiver_voltage_timer.cancel();
532                         receiver_voltage_timer.purge();
533                         receiver_voltage_timer = null;
534                 }
535         }
536
537         private void start_receiver_voltage_timer() {
538                 if (receiver_voltage_timer == null && altos_link.has_monitor_battery()) {
539                         receiver_voltage_timer = new Timer();
540                         receiver_voltage_timer.scheduleAtFixedRate(new TimerTask() { public void run() {update_receiver_voltage();}}, 1000L, 10000L);
541                 }
542         }
543
544         private void connected() throws InterruptedException {
545                 AltosDebug.debug("connected top");
546                 AltosDebug.check_ui("connected\n");
547                 try {
548                         if (altos_link == null)
549                                 throw new InterruptedException("no bluetooth");
550                         telemetry_state.config = altos_link.config_data();
551                         altos_link.set_radio_frequency(telemetry_state.frequency);
552                         altos_link.set_telemetry_rate(telemetry_state.telemetry_rate);
553                 } catch (TimeoutException e) {
554                         // If this timed out, then we really want to retry it, but
555                         // probably safer to just retry the connection from scratch.
556                         AltosDebug.debug("connected timeout");
557                         if (address != null) {
558                                 AltosDebug.debug("connected timeout, retrying");
559                                 start_altos_bluetooth(address, true);
560                         } else {
561                                 handler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
562                                 disconnect(true);
563                         }
564                         return;
565                 }
566
567                 AltosDebug.debug("connected bluetooth configured");
568                 telemetry_state.connect = TelemetryState.CONNECT_CONNECTED;
569                 telemetry_state.address = address;
570
571                 telemetry_start();
572
573                 AltosDebug.debug("connected TelemetryReader started");
574
575                 telemetry_logger = new TelemetryLogger(this, altos_link);
576
577                 start_receiver_voltage_timer();
578
579                 AltosDebug.debug("Notify UI of connection");
580
581                 send_to_clients();
582         }
583
584
585         @Override
586         public void onCreate() {
587
588                 AltosDebug.init(this);
589
590                 // Initialise preferences
591                 AltosDroidPreferences.init(this);
592
593                 // Get local Bluetooth adapter
594                 bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
595
596                 telemetry_state = new TelemetryState();
597
598                 // Create a reference to the NotificationManager so that we can update our notifcation text later
599                 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
600
601                 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
602                 telemetry_state.address = null;
603
604                 /* Pull the saved state information out of the preferences database
605                  */
606                 ArrayList<Integer> serials = AltosPreferences.list_states();
607
608                 telemetry_state.latest_serial = AltosPreferences.latest_state();
609
610                 telemetry_state.quiet = true;
611
612                 AltosDebug.debug("latest serial %d\n", telemetry_state.latest_serial);
613
614                 for (int serial : serials) {
615                         AltosState saved_state = AltosPreferences.state(serial);
616                         if (saved_state != null) {
617                                 if (telemetry_state.latest_serial == 0)
618                                         telemetry_state.latest_serial = serial;
619
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.states.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 Notification.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                 telemetry_state.states.put(state.cal_data().serial, state);
713                 telemetry_state.receiver_battery = listener_state.battery;
714                 send_to_clients();
715         }
716
717         public void failed() {
718         }
719
720         public void error(String reason) {
721                 stop_idle_monitor();
722         }
723 }