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