2 * Copyright © 2012 Mike Beattie <mike@ethernal.org>
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.
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.
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.
19 package org.altusmetrum.AltosDroid;
21 import java.lang.ref.WeakReference;
22 import java.util.concurrent.TimeoutException;
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;
34 import android.widget.Toast;
35 import androidx.core.app.NotificationCompat;
37 import org.altusmetrum.altoslib_14.*;
39 public class TelemetryService extends Service implements AltosIdleMonitorListener {
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;
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;
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.
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;
76 // Local Bluetooth adapter
77 private BluetoothAdapter bluetooth_adapter = null;
79 // Last data seen; send to UI when it starts
80 private TelemetryState telemetry_state;
82 // Idle monitor if active
83 AltosIdleMonitor idle_monitor = null;
86 AltosIgnite ignite = null;
87 boolean ignite_running;
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); }
95 public void handleMessage(Message msg) {
96 DeviceAddress address;
98 TelemetryService s = service.get();
99 AltosDroidLink bt = null;
105 /* Messages from application */
106 case MSG_REGISTER_CLIENT:
107 s.add_client(msg.replyTo);
109 case MSG_UNREGISTER_CLIENT:
110 s.remove_client(msg.replyTo);
113 AltosDebug.debug("Connect command received");
114 address = (DeviceAddress) msg.obj;
115 AltosDroidPreferences.set_active_device(address);
116 s.start_altos_bluetooth(address, false);
119 AltosDebug.debug("Open USB command received");
120 UsbDevice device = (UsbDevice) msg.obj;
124 AltosDebug.debug("Disconnect command received");
126 if (!(Boolean) msg.obj)
127 AltosDroidPreferences.set_active_device(null);
130 case MSG_DELETE_SERIAL:
131 AltosDebug.debug("Delete Serial command received");
132 s.delete_serial((Integer) msg.obj);
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) {
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) {
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();
160 *Messages from AltosBluetooth
163 AltosDebug.debug("MSG_CONNECTED");
164 bt = (AltosDroidLink) msg.obj;
166 if (bt != s.altos_link) {
167 AltosDebug.debug("Stale message");
170 AltosDebug.debug("Connected to device");
173 } catch (InterruptedException ie) {
176 case MSG_CONNECT_FAILED:
177 AltosDebug.debug("MSG_CONNECT_FAILED");
178 bt = (AltosDroidLink) msg.obj;
180 if (bt != s.altos_link) {
181 AltosDebug.debug("Stale message");
184 if (s.address != null) {
185 AltosDebug.debug("Connection failed... retrying");
186 s.start_altos_bluetooth(s.address, true);
191 case MSG_DISCONNECTED:
193 /* This can be sent by either AltosDroidLink or TelemetryReader */
194 AltosDebug.debug("MSG_DISCONNECTED");
195 bt = (AltosDroidLink) msg.obj;
197 if (bt != s.altos_link) {
198 AltosDebug.debug("Stale message");
201 if (s.address != null) {
202 AltosDebug.debug("Connection lost... retrying");
203 s.start_altos_bluetooth(s.address, true);
210 * Messages from TelemetryReader
213 s.telemetry((AltosTelemetry) msg.obj);
216 // forward crc error messages
217 s.telemetry_state.crc_errors = (Integer) msg.obj;
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);
226 case MSG_MONITOR_IDLE_START:
227 AltosDebug.debug("start monitor idle");
228 s.start_idle_monitor();
230 case MSG_MONITOR_IDLE_STOP:
231 AltosDebug.debug("stop monitor idle");
232 s.stop_idle_monitor();
235 AltosDebug.debug("reboot");
238 case MSG_IGNITER_QUERY:
239 AltosDebug.debug("igniter query");
240 s.igniter_query(msg.replyTo);
242 case MSG_IGNITER_FIRE:
243 AltosDebug.debug("igniter fire");
244 s.igniter_fire((String) msg.obj);
247 super.handleMessage(msg);
252 /* Handle telemetry packet
254 private void telemetry(AltosTelemetry telem) {
257 state = telemetry_state.get(telem.serial());
259 state = new AltosState(new AltosCalData());
260 telem.provide_data(state);
261 telemetry_state.put(telem.serial(), state);
262 telemetry_state.quiet = false;
264 AltosPreferences.set_state(state,telem.serial());
269 /* Construct the message to deliver to clients
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);
277 /* A new friend has connected
279 private void add_client(Messenger client) {
282 AltosDebug.debug("Client bound to service");
284 /* On connect, send the current state to the new client
286 send_to_client(client);
287 send_idle_mode_to_client(client);
289 /* If we've got an address from a previous session, then
290 * go ahead and try to reconnect to the device
292 if (address != null && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
293 AltosDebug.debug("Reconnecting now...");
294 start_altos_bluetooth(address, false);
298 /* A client has disconnected, clean up
300 private void remove_client(Messenger client) {
301 clients.remove(client);
302 AltosDebug.debug("Client unbound from service");
304 /* When the list of clients is empty, stop the service if
305 * we have no current telemetry source
308 if (clients.isEmpty() && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
309 AltosDebug.debug("No clients, no connection. Stopping\n");
314 private void send_to_client(Messenger client) {
315 Message m = message();
318 } catch (RemoteException e) {
319 AltosDebug.error("Client %s disappeared", client.toString());
320 remove_client(client);
324 private void send_to_clients() {
325 for (Messenger client : clients)
326 send_to_client(client);
329 private void send_idle_mode_to_client(Messenger client) {
330 Message m = Message.obtain(null, AltosDroid.MSG_IDLE_MODE, idle_monitor != null);
333 } catch (RemoteException e) {
334 AltosDebug.error("Client %s disappeared", client.toString());
335 remove_client(client);
339 private void send_idle_mode_to_clients() {
340 for (Messenger client : clients)
341 send_idle_mode_to_client(client);
344 private void send_file_failed_to_client(Messenger client, File f) {
345 Message m = Message.obtain(null, AltosDroid.MSG_FILE_FAILED, f);
348 } catch (RemoteException e) {
349 AltosDebug.error("Client %s disappeared", client.toString());
350 remove_client(client);
354 public void send_file_failed_to_clients(File f) {
355 for (Messenger client : clients)
356 send_file_failed_to_client(client, f);
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();
366 private void telemetry_stop() {
367 if (telemetry_reader != null) {
368 AltosDebug.debug("disconnect(): stopping TelemetryReader");
369 telemetry_reader.interrupt();
371 telemetry_reader.join();
372 } catch (InterruptedException e) {
374 telemetry_reader = null;
378 private void disconnect(boolean notify) {
379 AltosDebug.debug("disconnect(): begin");
381 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
382 telemetry_state.address = null;
384 if (idle_monitor != null)
387 if (altos_link != null)
388 altos_link.closing();
390 stop_receiver_voltage_timer();
393 if (telemetry_logger != null) {
394 AltosDebug.debug("disconnect(): stopping TelemetryLogger");
395 telemetry_logger.stop();
396 telemetry_logger = null;
398 if (altos_link != null) {
399 AltosDebug.debug("disconnect(): stopping AltosDroidLink");
404 telemetry_state.config = null;
406 AltosDebug.debug("disconnect(): send message to clients");
408 if (clients.isEmpty()) {
409 AltosDebug.debug("disconnect(): no clients, terminating");
415 private void start_usb(UsbDevice device) {
416 AltosUsb d = new AltosUsb(this, device, handler);
423 } catch (InterruptedException ie) {
428 private void delete_serial(int serial) {
429 telemetry_state.remove(serial);
430 AltosPreferences.remove_state(serial);
434 private void start_altos_bluetooth(DeviceAddress address, boolean pause) {
435 if (bluetooth_adapter == null || !bluetooth_adapter.isEnabled() || address.address == null)
440 // Get the BluetoothDevice object
441 BluetoothDevice device = bluetooth_adapter.getRemoteDevice(address.address);
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;
451 private void start_idle_monitor() {
452 if (altos_link != null && idle_monitor == null) {
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();
463 private void stop_idle_monitor() {
464 if (idle_monitor != null) {
466 idle_monitor.abort();
467 } catch (InterruptedException ie) {
470 telemetry_state.idle_mode = false;
472 send_idle_mode_to_clients();
476 private void reboot_remote() {
477 if (altos_link != null) {
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) {
487 altos_link.stop_remote();
488 } catch (InterruptedException ie) {
494 private void ensure_ignite() {
496 ignite = new AltosIgnite(altos_link, true, false);
499 private synchronized void igniter_query(Messenger client) {
501 HashMap<String,Integer> status_map = null;
502 ignite_running = true;
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");
513 ignite_running = false;
515 Message m = Message.obtain(null, AltosDroid.MSG_IGNITER_STATUS, status_map);
518 } catch (RemoteException e) {
522 private synchronized void igniter_fire(String igniter) {
524 ignite_running = true;
527 ignite.fire(igniter);
528 } catch (InterruptedException ie) {
530 ignite_running = false;
534 // Timer for receiver battery voltage monitoring
535 Timer receiver_voltage_timer;
537 private void update_receiver_voltage() {
538 if (altos_link != null && idle_monitor == null && !ignite_running) {
540 double voltage = altos_link.monitor_battery();
541 telemetry_state.receiver_battery = voltage;
543 } catch (InterruptedException ie) {
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;
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);
563 private void connected() throws InterruptedException {
564 AltosDebug.debug("connected top");
565 AltosDebug.check_ui("connected\n");
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);
580 handler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
586 AltosDebug.debug("connected bluetooth configured");
587 telemetry_state.connect = TelemetryState.CONNECT_CONNECTED;
588 telemetry_state.address = address;
592 AltosDebug.debug("connected TelemetryReader started");
594 telemetry_logger = new TelemetryLogger(this, altos_link);
596 start_receiver_voltage_timer();
598 AltosDebug.debug("Notify UI of connection");
605 public void onCreate() {
607 AltosDebug.init(this);
609 // Initialise preferences
610 AltosDroidPreferences.init(this);
612 // Get local Bluetooth adapter
613 bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
615 telemetry_state = new TelemetryState();
617 // Create a reference to the NotificationManager so that we can update our notifcation text later
618 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
620 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
621 telemetry_state.address = null;
623 /* Pull the saved state information out of the preferences database
625 ArrayList<Integer> serials = AltosPreferences.list_states();
627 telemetry_state.latest_serial = AltosPreferences.latest_state();
629 telemetry_state.quiet = true;
631 AltosDebug.debug("latest serial %d\n", telemetry_state.latest_serial);
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",
638 saved_state.cal_data().flight);
639 if (saved_state.gps != null)
640 AltosDebug.debug("\tposition %f,%f",
642 saved_state.gps.lon);
643 telemetry_state.put(serial, saved_state);
645 AltosDebug.debug("Failed to recover state for %d", serial);
646 AltosPreferences.remove_state(serial);
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);
663 public int onStartCommand(Intent intent, int flags, int startId) {
664 AltosDebug.debug("Received start id %d: %s", startId, intent);
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);
671 (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
672 ? createNotificationChannel("altosdroid_telemetry", "AltosDroid Telemetry Service")
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())
682 .setSmallIcon(R.drawable.am_status_c)
683 // .setLargeIcon(R.drawable.am_status_c)
686 // Move us into the foreground.
687 startForeground(NOTIFICATION, notification);
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))
694 String action = intent.getAction();
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);
703 // We want this service to continue running until it is explicitly
704 // stopped, so return sticky.
709 public void onDestroy() {
711 // Stop the bluetooth Comms threads
714 // Demote us from the foreground, and cancel the persistent notification.
715 stopForeground(true);
717 // Tell the user we stopped.
718 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
722 public IBinder onBind(Intent intent) {
723 return messenger.getBinder();
726 /* AltosIdleMonitorListener */
727 public void update(AltosState state, AltosListenerState listener_state) {
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;
735 public void failed() {
738 public void error(String reason) {