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