2bec95bc4cf1d05de95ac472ff4c73ec81cb1e1d
[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                 state = telemetry_state.get(telem.serial());
255                 if (state == null)
256                         state = new AltosState(new AltosCalData());
257                 telem.provide_data(state);
258                 telemetry_state.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                 return Message.obtain(null, AltosDroid.MSG_STATE, telemetry_state);
272         }
273
274         /* A new friend has connected
275          */
276         private void add_client(Messenger client) {
277
278                 clients.add(client);
279                 AltosDebug.debug("Client bound to service");
280
281                 /* On connect, send the current state to the new client
282                  */
283                 send_to_client(client);
284                 send_idle_mode_to_client(client);
285
286                 /* If we've got an address from a previous session, then
287                  * go ahead and try to reconnect to the device
288                  */
289                 if (address != null && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
290                         AltosDebug.debug("Reconnecting now...");
291                         start_altos_bluetooth(address, false);
292                 }
293         }
294
295         /* A client has disconnected, clean up
296          */
297         private void remove_client(Messenger client) {
298                 clients.remove(client);
299                 AltosDebug.debug("Client unbound from service");
300
301                 /* When the list of clients is empty, stop the service if
302                  * we have no current telemetry source
303                  */
304
305                  if (clients.isEmpty() && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
306                          AltosDebug.debug("No clients, no connection. Stopping\n");
307                          stopSelf();
308                  }
309         }
310
311         private void send_to_client(Messenger client) {
312                 Message m = message();
313                 try {
314                         client.send(m);
315                 } catch (RemoteException e) {
316                         AltosDebug.error("Client %s disappeared", client.toString());
317                         remove_client(client);
318                 }
319         }
320
321         private void send_to_clients() {
322                 for (Messenger client : clients)
323                         send_to_client(client);
324         }
325
326         private void send_idle_mode_to_client(Messenger client) {
327                 Message m = Message.obtain(null, AltosDroid.MSG_IDLE_MODE, idle_monitor != null);
328                 try {
329                         client.send(m);
330                 } catch (RemoteException e) {
331                         AltosDebug.error("Client %s disappeared", client.toString());
332                         remove_client(client);
333                 }
334         }
335
336         private void send_idle_mode_to_clients() {
337                 for (Messenger client : clients)
338                         send_idle_mode_to_client(client);
339         }
340
341         private void telemetry_start() {
342                 if (telemetry_reader == null && idle_monitor == null && !ignite_running) {
343                         telemetry_reader = new TelemetryReader(altos_link, handler);
344                         telemetry_reader.start();
345                 }
346         }
347
348         private void telemetry_stop() {
349                 if (telemetry_reader != null) {
350                         AltosDebug.debug("disconnect(): stopping TelemetryReader");
351                         telemetry_reader.interrupt();
352                         try {
353                                 telemetry_reader.join();
354                         } catch (InterruptedException e) {
355                         }
356                         telemetry_reader = null;
357                 }
358         }
359
360         private void disconnect(boolean notify) {
361                 AltosDebug.debug("disconnect(): begin");
362
363                 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
364                 telemetry_state.address = null;
365
366                 if (idle_monitor != null)
367                         stop_idle_monitor();
368
369                 if (altos_link != null)
370                         altos_link.closing();
371
372                 stop_receiver_voltage_timer();
373
374                 telemetry_stop();
375                 if (telemetry_logger != null) {
376                         AltosDebug.debug("disconnect(): stopping TelemetryLogger");
377                         telemetry_logger.stop();
378                         telemetry_logger = null;
379                 }
380                 if (altos_link != null) {
381                         AltosDebug.debug("disconnect(): stopping AltosDroidLink");
382                         altos_link.close();
383                         altos_link = null;
384                         ignite = null;
385                 }
386                 telemetry_state.config = null;
387                 if (notify) {
388                         AltosDebug.debug("disconnect(): send message to clients");
389                         send_to_clients();
390                         if (clients.isEmpty()) {
391                                 AltosDebug.debug("disconnect(): no clients, terminating");
392                                 stopSelf();
393                         }
394                 }
395         }
396
397         private void start_usb(UsbDevice device) {
398                 AltosUsb        d = new AltosUsb(this, device, handler);
399
400                 if (d != null) {
401                         disconnect(false);
402                         altos_link = d;
403                         try {
404                                 connected();
405                         } catch (InterruptedException ie) {
406                         }
407                 }
408         }
409
410         private void delete_serial(int serial) {
411                 telemetry_state.remove(serial);
412                 AltosPreferences.remove_state(serial);
413                 send_to_clients();
414         }
415
416         private void start_altos_bluetooth(DeviceAddress address, boolean pause) {
417                 if (bluetooth_adapter == null || !bluetooth_adapter.isEnabled())
418                         return;
419
420                 disconnect(false);
421
422                 // Get the BluetoothDevice object
423                 BluetoothDevice device = bluetooth_adapter.getRemoteDevice(address.address);
424
425                 this.address = address;
426                 AltosDebug.debug("start_altos_bluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress());
427                 altos_link = new AltosBluetooth(device, handler, pause);
428                 telemetry_state.connect = TelemetryState.CONNECT_CONNECTING;
429                 telemetry_state.address = address;
430                 send_to_clients();
431         }
432
433         private void start_idle_monitor() {
434                 if (altos_link != null && idle_monitor == null) {
435                         telemetry_stop();
436                         idle_monitor = new AltosIdleMonitor(this, altos_link, true, false);
437                         idle_monitor.set_callsign(AltosPreferences.callsign());
438                         idle_monitor.set_frequency(telemetry_state.frequency);
439                         telemetry_state.idle_mode = true;
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_state.idle_mode = false;
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                                 AltosDebug.debug("recovered old state serial %d flight %d",
619                                                  serial,
620                                                  saved_state.cal_data().flight);
621                                 if (saved_state.gps != null)
622                                         AltosDebug.debug("\tposition %f,%f",
623                                                          saved_state.gps.lat,
624                                                          saved_state.gps.lon);
625                                 telemetry_state.put(serial, saved_state);
626                         } else {
627                                 AltosDebug.debug("Failed to recover state for %d", serial);
628                                 AltosPreferences.remove_state(serial);
629                         }
630                 }
631         }
632
633
634         private String createNotificationChannel(String channelId, String channelName) {
635                 NotificationChannel chan = new NotificationChannel(
636                                 channelId, channelName, NotificationManager.IMPORTANCE_NONE);
637                 chan.setLightColor(Color.BLUE);
638                 chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
639                 NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
640                 service.createNotificationChannel(chan);
641                 return channelId;
642         }
643
644         @Override
645         public int onStartCommand(Intent intent, int flags, int startId) {
646                 AltosDebug.debug("Received start id %d: %s", startId, intent);
647
648                 // The PendingIntent to launch our activity if the user selects this notification
649                 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
650                                 new Intent(this, AltosDroid.class), 0);
651
652                 String channelId =
653                                 (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
654                                                 ? createNotificationChannel("altosdroid_telemetry", "AltosDroid Telemetry Service")
655                                                 : "";
656
657                 // Create notification to be displayed while the service runs
658                 Notification notification = new NotificationCompat.Builder(this, channelId)
659                                 .setContentTitle(getText(R.string.telemetry_service_label))
660                                 .setContentText(getText(R.string.telemetry_service_started))
661                                 .setContentIntent(contentIntent)
662                                 .setWhen(System.currentTimeMillis())
663                                 .setOngoing(true)
664                                 .setSmallIcon(R.drawable.am_status_c)
665 //                              .setLargeIcon(R.drawable.am_status_c)
666                                 .build();
667
668                 // Move us into the foreground.
669                 startForeground(NOTIFICATION, notification);
670
671                 /* Start bluetooth if we don't have a connection already */
672                 if (intent != null &&
673                     (telemetry_state.connect == TelemetryState.CONNECT_NONE ||
674                      telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED))
675                 {
676                         String  action = intent.getAction();
677
678                         if (action.equals(AltosDroid.ACTION_BLUETOOTH)) {
679                                 DeviceAddress address = AltosDroidPreferences.active_device();
680                                 if (address != null && !address.address.startsWith("USB"))
681                                         start_altos_bluetooth(address, false);
682                         }
683                 }
684
685                 // We want this service to continue running until it is explicitly
686                 // stopped, so return sticky.
687                 return START_STICKY;
688         }
689
690         @Override
691         public void onDestroy() {
692
693                 // Stop the bluetooth Comms threads
694                 disconnect(true);
695
696                 // Demote us from the foreground, and cancel the persistent notification.
697                 stopForeground(true);
698
699                 // Tell the user we stopped.
700                 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
701         }
702
703         @Override
704         public IBinder onBind(Intent intent) {
705                 return messenger.getBinder();
706         }
707
708         /* AltosIdleMonitorListener */
709         public void update(AltosState state, AltosListenerState listener_state) {
710                 if (state != null)
711                         AltosDebug.debug("update call %s freq %7.3f", state.cal_data().callsign, state.frequency);
712                 telemetry_state.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 }