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.os.Build.*;
35 import android.widget.Toast;
36 import androidx.core.app.NotificationCompat;
38 import org.altusmetrum.altoslib_14.*;
40 public class TelemetryService extends Service implements AltosIdleMonitorListener {
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;
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;
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.
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;
77 // Local Bluetooth adapter
78 private BluetoothAdapter bluetooth_adapter = null;
80 // Last data seen; send to UI when it starts
81 private TelemetryState telemetry_state;
83 // Idle monitor if active
84 AltosIdleMonitor idle_monitor = null;
87 AltosIgnite ignite = null;
88 boolean ignite_running;
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); }
96 public void handleMessage(Message msg) {
97 DeviceAddress address;
99 TelemetryService s = service.get();
100 AltosDroidLink bt = null;
106 /* Messages from application */
107 case MSG_REGISTER_CLIENT:
108 s.add_client(msg.replyTo);
110 case MSG_UNREGISTER_CLIENT:
111 s.remove_client(msg.replyTo);
114 AltosDebug.debug("Connect command received");
115 address = (DeviceAddress) msg.obj;
116 AltosDroidPreferences.set_active_device(address);
117 s.start_altos_bluetooth(address, false);
120 AltosDebug.debug("Open USB command received");
121 UsbDevice device = (UsbDevice) msg.obj;
125 AltosDebug.debug("Disconnect command received");
127 if (!(Boolean) msg.obj)
128 AltosDroidPreferences.set_active_device(null);
131 case MSG_DELETE_SERIAL:
132 AltosDebug.debug("Delete Serial command received");
133 s.delete_serial((Integer) msg.obj);
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) {
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) {
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();
161 *Messages from AltosBluetooth
164 AltosDebug.debug("MSG_CONNECTED");
165 bt = (AltosDroidLink) msg.obj;
167 if (bt != s.altos_link) {
168 AltosDebug.debug("Stale message");
171 AltosDebug.debug("Connected to device");
174 } catch (InterruptedException ie) {
177 case MSG_CONNECT_FAILED:
178 AltosDebug.debug("MSG_CONNECT_FAILED");
179 bt = (AltosDroidLink) msg.obj;
181 if (bt != s.altos_link) {
182 AltosDebug.debug("Stale message");
185 if (s.address != null) {
186 AltosDebug.debug("Connection failed... retrying");
187 s.start_altos_bluetooth(s.address, true);
192 case MSG_DISCONNECTED:
194 /* This can be sent by either AltosDroidLink or TelemetryReader */
195 AltosDebug.debug("MSG_DISCONNECTED");
196 bt = (AltosDroidLink) msg.obj;
198 if (bt != s.altos_link) {
199 AltosDebug.debug("Stale message");
202 if (s.address != null) {
203 AltosDebug.debug("Connection lost... retrying");
204 s.start_altos_bluetooth(s.address, true);
211 * Messages from TelemetryReader
214 s.telemetry((AltosTelemetry) msg.obj);
217 // forward crc error messages
218 s.telemetry_state.crc_errors = (Integer) msg.obj;
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);
227 case MSG_MONITOR_IDLE_START:
228 AltosDebug.debug("start monitor idle");
229 s.start_idle_monitor();
231 case MSG_MONITOR_IDLE_STOP:
232 AltosDebug.debug("stop monitor idle");
233 s.stop_idle_monitor();
236 AltosDebug.debug("reboot");
239 case MSG_IGNITER_QUERY:
240 AltosDebug.debug("igniter query");
241 s.igniter_query(msg.replyTo);
243 case MSG_IGNITER_FIRE:
244 AltosDebug.debug("igniter fire");
245 s.igniter_fire((String) msg.obj);
248 super.handleMessage(msg);
253 /* Handle telemetry packet
255 private void telemetry(AltosTelemetry telem) {
258 state = telemetry_state.get(telem.serial());
260 state = new AltosState(new AltosCalData());
261 telem.provide_data(state);
262 telemetry_state.put(telem.serial(), state);
263 telemetry_state.quiet = false;
265 AltosPreferences.set_state(state,telem.serial());
270 /* Construct the message to deliver to clients
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);
278 /* A new friend has connected
280 private void add_client(Messenger client) {
283 AltosDebug.debug("Client bound to service");
285 /* On connect, send the current state to the new client
287 send_to_client(client);
288 send_idle_mode_to_client(client);
290 /* If we've got an address from a previous session, then
291 * go ahead and try to reconnect to the device
293 if (address != null && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
294 AltosDebug.debug("Reconnecting now...");
295 start_altos_bluetooth(address, false);
299 /* A client has disconnected, clean up
301 private void remove_client(Messenger client) {
302 clients.remove(client);
303 AltosDebug.debug("Client unbound from service");
305 /* When the list of clients is empty, stop the service if
306 * we have no current telemetry source
309 if (clients.isEmpty() && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
310 AltosDebug.debug("No clients, no connection. Stopping\n");
315 private void send_to_client(Messenger client) {
316 Message m = message();
319 } catch (RemoteException e) {
320 AltosDebug.error("Client %s disappeared", client.toString());
321 remove_client(client);
325 private void send_to_clients() {
326 for (Messenger client : clients)
327 send_to_client(client);
330 private void send_idle_mode_to_client(Messenger client) {
331 Message m = Message.obtain(null, AltosDroid.MSG_IDLE_MODE, idle_monitor != null);
334 } catch (RemoteException e) {
335 AltosDebug.error("Client %s disappeared", client.toString());
336 remove_client(client);
340 private void send_idle_mode_to_clients() {
341 for (Messenger client : clients)
342 send_idle_mode_to_client(client);
345 private void send_file_failed_to_client(Messenger client, File f) {
346 Message m = Message.obtain(null, AltosDroid.MSG_FILE_FAILED, f);
349 } catch (RemoteException e) {
350 AltosDebug.error("Client %s disappeared", client.toString());
351 remove_client(client);
355 public void send_file_failed_to_clients(File f) {
356 for (Messenger client : clients)
357 send_file_failed_to_client(client, f);
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();
367 private void telemetry_stop() {
368 if (telemetry_reader != null) {
369 AltosDebug.debug("disconnect(): stopping TelemetryReader");
370 telemetry_reader.interrupt();
372 telemetry_reader.join();
373 } catch (InterruptedException e) {
375 telemetry_reader = null;
379 private void disconnect(boolean notify) {
380 AltosDebug.debug("disconnect(): begin");
382 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
383 telemetry_state.address = null;
385 if (idle_monitor != null)
388 if (altos_link != null)
389 altos_link.closing();
391 stop_receiver_voltage_timer();
394 if (telemetry_logger != null) {
395 AltosDebug.debug("disconnect(): stopping TelemetryLogger");
396 telemetry_logger.stop();
397 telemetry_logger = null;
399 if (altos_link != null) {
400 AltosDebug.debug("disconnect(): stopping AltosDroidLink");
405 telemetry_state.config = null;
407 AltosDebug.debug("disconnect(): send message to clients");
409 if (clients.isEmpty()) {
410 AltosDebug.debug("disconnect(): no clients, terminating");
416 private void start_usb(UsbDevice device) {
417 AltosUsb d = new AltosUsb(this, device, handler);
424 } catch (InterruptedException ie) {
429 private void delete_serial(int serial) {
430 telemetry_state.remove(serial);
431 AltosPreferences.remove_state(serial);
435 private void start_altos_bluetooth(DeviceAddress address, boolean pause) {
436 if (bluetooth_adapter == null || !bluetooth_adapter.isEnabled() || address.address == null)
441 // Get the BluetoothDevice object
442 BluetoothDevice device = bluetooth_adapter.getRemoteDevice(address.address);
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;
452 private void start_idle_monitor() {
453 if (altos_link != null && idle_monitor == null) {
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();
464 private void stop_idle_monitor() {
465 if (idle_monitor != null) {
467 idle_monitor.abort();
468 } catch (InterruptedException ie) {
471 telemetry_state.idle_mode = false;
473 send_idle_mode_to_clients();
477 private void reboot_remote() {
478 if (altos_link != null) {
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) {
488 altos_link.stop_remote();
489 } catch (InterruptedException ie) {
495 private void ensure_ignite() {
497 ignite = new AltosIgnite(altos_link, true, false);
500 private synchronized void igniter_query(Messenger client) {
502 HashMap<String,Integer> status_map = null;
503 ignite_running = true;
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");
514 ignite_running = false;
516 Message m = Message.obtain(null, AltosDroid.MSG_IGNITER_STATUS, status_map);
519 } catch (RemoteException e) {
523 private synchronized void igniter_fire(String igniter) {
525 ignite_running = true;
528 ignite.fire(igniter);
529 } catch (InterruptedException ie) {
531 ignite_running = false;
535 // Timer for receiver battery voltage monitoring
536 Timer receiver_voltage_timer;
538 private void update_receiver_voltage() {
539 if (altos_link != null && idle_monitor == null && !ignite_running) {
541 double voltage = altos_link.monitor_battery();
542 telemetry_state.receiver_battery = voltage;
544 } catch (InterruptedException ie) {
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;
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);
564 private void connected() throws InterruptedException {
565 AltosDebug.debug("connected top");
566 AltosDebug.check_ui("connected\n");
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);
581 handler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
587 AltosDebug.debug("connected bluetooth configured");
588 telemetry_state.connect = TelemetryState.CONNECT_CONNECTED;
589 telemetry_state.address = address;
593 AltosDebug.debug("connected TelemetryReader started");
595 telemetry_logger = new TelemetryLogger(this, altos_link);
597 start_receiver_voltage_timer();
599 AltosDebug.debug("Notify UI of connection");
606 public void onCreate() {
608 AltosDebug.init(this);
610 // Initialise preferences
611 AltosDroidPreferences.init(this);
613 // Get local Bluetooth adapter
614 bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
616 telemetry_state = new TelemetryState();
618 // Create a reference to the NotificationManager so that we can update our notifcation text later
619 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
621 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
622 telemetry_state.address = null;
624 /* Pull the saved state information out of the preferences database
626 ArrayList<Integer> serials = AltosPreferences.list_states();
628 telemetry_state.latest_serial = AltosPreferences.latest_state();
630 telemetry_state.quiet = true;
632 AltosDebug.debug("latest serial %d\n", telemetry_state.latest_serial);
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",
639 saved_state.cal_data().flight);
640 if (saved_state.gps != null)
641 AltosDebug.debug("\tposition %f,%f",
643 saved_state.gps.lon);
644 telemetry_state.put(serial, saved_state);
646 AltosDebug.debug("Failed to recover state for %d", serial);
647 AltosPreferences.remove_state(serial);
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);
664 public int onStartCommand(Intent intent, int flags, int startId) {
665 AltosDebug.debug("Received start id %d: %s", startId, intent);
668 if (android.os.Build.VERSION.SDK_INT >= 31) // android.os.Build.VERSION_CODES.S
669 flag = 33554432; // PendingIntent.FLAG_MUTABLE
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);
678 (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
679 ? createNotificationChannel("altosdroid_telemetry", "AltosDroid Telemetry Service")
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())
689 .setSmallIcon(R.drawable.am_status_c)
690 // .setLargeIcon(R.drawable.am_status_c)
693 // Move us into the foreground.
694 startForeground(NOTIFICATION, notification);
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))
701 String action = intent.getAction();
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);
710 // We want this service to continue running until it is explicitly
711 // stopped, so return sticky.
716 public void onDestroy() {
718 // Stop the bluetooth Comms threads
721 // Demote us from the foreground, and cancel the persistent notification.
722 stopForeground(true);
724 // Tell the user we stopped.
725 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
729 public IBinder onBind(Intent intent) {
730 return messenger.getBinder();
733 /* AltosIdleMonitorListener */
734 public void update(AltosState state, AltosListenerState listener_state) {
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;
742 public void failed() {
745 public void error(String reason) {