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;
26 import android.bluetooth.BluetoothDevice;
27 import android.bluetooth.BluetoothAdapter;
28 import android.graphics.Color;
29 import android.hardware.usb.*;
30 import android.content.Intent;
31 import android.content.Context;
33 import android.widget.Toast;
34 import androidx.core.app.NotificationCompat;
36 import org.altusmetrum.altoslib_14.*;
38 public class TelemetryService extends Service implements AltosIdleMonitorListener {
40 static final int MSG_REGISTER_CLIENT = 1;
41 static final int MSG_UNREGISTER_CLIENT = 2;
42 static final int MSG_CONNECT = 3;
43 static final int MSG_OPEN_USB = 4;
44 static final int MSG_CONNECTED = 5;
45 static final int MSG_CONNECT_FAILED = 6;
46 static final int MSG_DISCONNECTED = 7;
47 static final int MSG_TELEMETRY = 8;
48 static final int MSG_SETFREQUENCY = 9;
49 static final int MSG_CRC_ERROR = 10;
50 static final int MSG_SETBAUD = 11;
51 static final int MSG_DISCONNECT = 12;
52 static final int MSG_DELETE_SERIAL = 13;
53 static final int MSG_BLUETOOTH_ENABLED = 14;
54 static final int MSG_MONITOR_IDLE_START= 15;
55 static final int MSG_MONITOR_IDLE_STOP = 16;
56 static final int MSG_REBOOT = 17;
57 static final int MSG_IGNITER_QUERY = 18;
58 static final int MSG_IGNITER_FIRE = 19;
60 // Unique Identification Number for the Notification.
61 // We use it on Notification start, and to cancel it.
62 private int NOTIFICATION = R.string.telemetry_service_label;
63 //private NotificationManager mNM;
65 ArrayList<Messenger> clients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
66 final Handler handler = new IncomingHandler(this);
67 final Messenger messenger = new Messenger(handler); // Target we publish for clients to send messages to IncomingHandler.
69 // Name of the connected device
70 DeviceAddress address;
71 private AltosDroidLink altos_link = null;
72 private TelemetryReader telemetry_reader = null;
73 private TelemetryLogger telemetry_logger = null;
75 // Local Bluetooth adapter
76 private BluetoothAdapter bluetooth_adapter = null;
78 // Last data seen; send to UI when it starts
79 private TelemetryState telemetry_state;
81 // Idle monitor if active
82 AltosIdleMonitor idle_monitor = null;
85 AltosIgnite ignite = null;
86 boolean ignite_running;
88 // Handler of incoming messages from clients.
89 static class IncomingHandler extends Handler {
90 private final WeakReference<TelemetryService> service;
91 IncomingHandler(TelemetryService s) { service = new WeakReference<TelemetryService>(s); }
94 public void handleMessage(Message msg) {
95 DeviceAddress address;
97 TelemetryService s = service.get();
98 AltosDroidLink bt = null;
104 /* Messages from application */
105 case MSG_REGISTER_CLIENT:
106 s.add_client(msg.replyTo);
108 case MSG_UNREGISTER_CLIENT:
109 s.remove_client(msg.replyTo);
112 AltosDebug.debug("Connect command received");
113 address = (DeviceAddress) msg.obj;
114 AltosDroidPreferences.set_active_device(address);
115 s.start_altos_bluetooth(address, false);
118 AltosDebug.debug("Open USB command received");
119 UsbDevice device = (UsbDevice) msg.obj;
123 AltosDebug.debug("Disconnect command received");
125 if (!(Boolean) msg.obj)
126 AltosDroidPreferences.set_active_device(null);
129 case MSG_DELETE_SERIAL:
130 AltosDebug.debug("Delete Serial command received");
131 s.delete_serial((Integer) msg.obj);
133 case MSG_SETFREQUENCY:
134 AltosDebug.debug("MSG_SETFREQUENCY");
135 s.telemetry_state.frequency = (Double) msg.obj;
136 if (s.idle_monitor != null) {
137 s.idle_monitor.set_frequency(s.telemetry_state.frequency);
138 } else if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
140 s.altos_link.set_radio_frequency(s.telemetry_state.frequency);
141 s.altos_link.save_frequency();
142 } catch (InterruptedException e) {
143 } catch (TimeoutException e) {
149 AltosDebug.debug("MSG_SETBAUD");
150 s.telemetry_state.telemetry_rate = (Integer) msg.obj;
151 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
152 s.altos_link.set_telemetry_rate(s.telemetry_state.telemetry_rate);
153 s.altos_link.save_telemetry_rate();
159 *Messages from AltosBluetooth
162 AltosDebug.debug("MSG_CONNECTED");
163 bt = (AltosDroidLink) msg.obj;
165 if (bt != s.altos_link) {
166 AltosDebug.debug("Stale message");
169 AltosDebug.debug("Connected to device");
172 } catch (InterruptedException ie) {
175 case MSG_CONNECT_FAILED:
176 AltosDebug.debug("MSG_CONNECT_FAILED");
177 bt = (AltosDroidLink) msg.obj;
179 if (bt != s.altos_link) {
180 AltosDebug.debug("Stale message");
183 if (s.address != null) {
184 AltosDebug.debug("Connection failed... retrying");
185 s.start_altos_bluetooth(s.address, true);
190 case MSG_DISCONNECTED:
192 /* This can be sent by either AltosDroidLink or TelemetryReader */
193 AltosDebug.debug("MSG_DISCONNECTED");
194 bt = (AltosDroidLink) msg.obj;
196 if (bt != s.altos_link) {
197 AltosDebug.debug("Stale message");
200 if (s.address != null) {
201 AltosDebug.debug("Connection lost... retrying");
202 s.start_altos_bluetooth(s.address, true);
209 * Messages from TelemetryReader
212 s.telemetry((AltosTelemetry) msg.obj);
215 // forward crc error messages
216 s.telemetry_state.crc_errors = (Integer) msg.obj;
219 case MSG_BLUETOOTH_ENABLED:
220 AltosDebug.debug("TelemetryService notes that BT is now enabled");
221 address = AltosDroidPreferences.active_device();
222 if (address != null && !address.address.startsWith("USB"))
223 s.start_altos_bluetooth(address, false);
225 case MSG_MONITOR_IDLE_START:
226 AltosDebug.debug("start monitor idle");
227 s.start_idle_monitor();
229 case MSG_MONITOR_IDLE_STOP:
230 AltosDebug.debug("stop monitor idle");
231 s.stop_idle_monitor();
234 AltosDebug.debug("reboot");
237 case MSG_IGNITER_QUERY:
238 AltosDebug.debug("igniter query");
239 s.igniter_query(msg.replyTo);
241 case MSG_IGNITER_FIRE:
242 AltosDebug.debug("igniter fire");
243 s.igniter_fire((String) msg.obj);
246 super.handleMessage(msg);
251 /* Handle telemetry packet
253 private void telemetry(AltosTelemetry telem) {
256 state = telemetry_state.get(telem.serial());
258 state = new AltosState(new AltosCalData());
259 telem.provide_data(state);
260 telemetry_state.put(telem.serial(), state);
261 telemetry_state.quiet = false;
263 AltosPreferences.set_state(state,telem.serial());
268 /* Construct the message to deliver to clients
270 private Message message() {
271 if (telemetry_state == null)
272 AltosDebug.debug("telemetry_state null!");
273 return Message.obtain(null, AltosDroid.MSG_STATE, telemetry_state);
276 /* A new friend has connected
278 private void add_client(Messenger client) {
281 AltosDebug.debug("Client bound to service");
283 /* On connect, send the current state to the new client
285 send_to_client(client);
286 send_idle_mode_to_client(client);
288 /* If we've got an address from a previous session, then
289 * go ahead and try to reconnect to the device
291 if (address != null && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
292 AltosDebug.debug("Reconnecting now...");
293 start_altos_bluetooth(address, false);
297 /* A client has disconnected, clean up
299 private void remove_client(Messenger client) {
300 clients.remove(client);
301 AltosDebug.debug("Client unbound from service");
303 /* When the list of clients is empty, stop the service if
304 * we have no current telemetry source
307 if (clients.isEmpty() && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
308 AltosDebug.debug("No clients, no connection. Stopping\n");
313 private void send_to_client(Messenger client) {
314 Message m = message();
317 } catch (RemoteException e) {
318 AltosDebug.error("Client %s disappeared", client.toString());
319 remove_client(client);
323 private void send_to_clients() {
324 for (Messenger client : clients)
325 send_to_client(client);
328 private void send_idle_mode_to_client(Messenger client) {
329 Message m = Message.obtain(null, AltosDroid.MSG_IDLE_MODE, idle_monitor != null);
332 } catch (RemoteException e) {
333 AltosDebug.error("Client %s disappeared", client.toString());
334 remove_client(client);
338 private void send_idle_mode_to_clients() {
339 for (Messenger client : clients)
340 send_idle_mode_to_client(client);
343 private void telemetry_start() {
344 if (telemetry_reader == null && idle_monitor == null && !ignite_running) {
345 telemetry_reader = new TelemetryReader(altos_link, handler);
346 telemetry_reader.start();
350 private void telemetry_stop() {
351 if (telemetry_reader != null) {
352 AltosDebug.debug("disconnect(): stopping TelemetryReader");
353 telemetry_reader.interrupt();
355 telemetry_reader.join();
356 } catch (InterruptedException e) {
358 telemetry_reader = null;
362 private void disconnect(boolean notify) {
363 AltosDebug.debug("disconnect(): begin");
365 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
366 telemetry_state.address = null;
368 if (idle_monitor != null)
371 if (altos_link != null)
372 altos_link.closing();
374 stop_receiver_voltage_timer();
377 if (telemetry_logger != null) {
378 AltosDebug.debug("disconnect(): stopping TelemetryLogger");
379 telemetry_logger.stop();
380 telemetry_logger = null;
382 if (altos_link != null) {
383 AltosDebug.debug("disconnect(): stopping AltosDroidLink");
388 telemetry_state.config = null;
390 AltosDebug.debug("disconnect(): send message to clients");
392 if (clients.isEmpty()) {
393 AltosDebug.debug("disconnect(): no clients, terminating");
399 private void start_usb(UsbDevice device) {
400 AltosUsb d = new AltosUsb(this, device, handler);
407 } catch (InterruptedException ie) {
412 private void delete_serial(int serial) {
413 telemetry_state.remove(serial);
414 AltosPreferences.remove_state(serial);
418 private void start_altos_bluetooth(DeviceAddress address, boolean pause) {
419 if (bluetooth_adapter == null || !bluetooth_adapter.isEnabled() || address.address == null)
424 // Get the BluetoothDevice object
425 BluetoothDevice device = bluetooth_adapter.getRemoteDevice(address.address);
427 this.address = address;
428 AltosDebug.debug("start_altos_bluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress());
429 altos_link = new AltosBluetooth(device, handler, pause);
430 telemetry_state.connect = TelemetryState.CONNECT_CONNECTING;
431 telemetry_state.address = address;
435 private void start_idle_monitor() {
436 if (altos_link != null && idle_monitor == null) {
438 idle_monitor = new AltosIdleMonitor(this, altos_link, true, false);
439 idle_monitor.set_callsign(AltosPreferences.callsign());
440 idle_monitor.set_frequency(telemetry_state.frequency);
441 telemetry_state.idle_mode = true;
442 idle_monitor.start();
443 send_idle_mode_to_clients();
447 private void stop_idle_monitor() {
448 if (idle_monitor != null) {
450 idle_monitor.abort();
451 } catch (InterruptedException ie) {
454 telemetry_state.idle_mode = false;
456 send_idle_mode_to_clients();
460 private void reboot_remote() {
461 if (altos_link != null) {
464 altos_link.start_remote();
465 altos_link.printf("r eboot\n");
466 altos_link.flush_output();
467 } catch (TimeoutException te) {
468 } catch (InterruptedException ie) {
471 altos_link.stop_remote();
472 } catch (InterruptedException ie) {
478 private void ensure_ignite() {
480 ignite = new AltosIgnite(altos_link, true, false);
483 private synchronized void igniter_query(Messenger client) {
485 HashMap<String,Integer> status_map = null;
486 ignite_running = true;
490 status_map = ignite.status();
491 } catch (InterruptedException ie) {
492 AltosDebug.debug("ignite.status interrupted");
493 } catch (TimeoutException te) {
494 AltosDebug.debug("ignite.status timeout");
497 ignite_running = false;
499 Message m = Message.obtain(null, AltosDroid.MSG_IGNITER_STATUS, status_map);
502 } catch (RemoteException e) {
506 private synchronized void igniter_fire(String igniter) {
508 ignite_running = true;
511 ignite.fire(igniter);
512 } catch (InterruptedException ie) {
514 ignite_running = false;
518 // Timer for receiver battery voltage monitoring
519 Timer receiver_voltage_timer;
521 private void update_receiver_voltage() {
522 if (altos_link != null && idle_monitor == null && !ignite_running) {
524 double voltage = altos_link.monitor_battery();
525 telemetry_state.receiver_battery = voltage;
527 } catch (InterruptedException ie) {
532 private void stop_receiver_voltage_timer() {
533 if (receiver_voltage_timer != null) {
534 receiver_voltage_timer.cancel();
535 receiver_voltage_timer.purge();
536 receiver_voltage_timer = null;
540 private void start_receiver_voltage_timer() {
541 if (receiver_voltage_timer == null && altos_link.has_monitor_battery()) {
542 receiver_voltage_timer = new Timer();
543 receiver_voltage_timer.scheduleAtFixedRate(new TimerTask() { public void run() {update_receiver_voltage();}}, 1000L, 10000L);
547 private void connected() throws InterruptedException {
548 AltosDebug.debug("connected top");
549 AltosDebug.check_ui("connected\n");
551 if (altos_link == null)
552 throw new InterruptedException("no bluetooth");
553 telemetry_state.config = altos_link.config_data();
554 altos_link.set_radio_frequency(telemetry_state.frequency);
555 altos_link.set_telemetry_rate(telemetry_state.telemetry_rate);
556 } catch (TimeoutException e) {
557 // If this timed out, then we really want to retry it, but
558 // probably safer to just retry the connection from scratch.
559 AltosDebug.debug("connected timeout");
560 if (address != null) {
561 AltosDebug.debug("connected timeout, retrying");
562 start_altos_bluetooth(address, true);
564 handler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
570 AltosDebug.debug("connected bluetooth configured");
571 telemetry_state.connect = TelemetryState.CONNECT_CONNECTED;
572 telemetry_state.address = address;
576 AltosDebug.debug("connected TelemetryReader started");
578 telemetry_logger = new TelemetryLogger(this, altos_link);
580 start_receiver_voltage_timer();
582 AltosDebug.debug("Notify UI of connection");
589 public void onCreate() {
591 AltosDebug.init(this);
593 // Initialise preferences
594 AltosDroidPreferences.init(this);
596 // Get local Bluetooth adapter
597 bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
599 telemetry_state = new TelemetryState();
601 // Create a reference to the NotificationManager so that we can update our notifcation text later
602 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
604 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
605 telemetry_state.address = null;
607 /* Pull the saved state information out of the preferences database
609 ArrayList<Integer> serials = AltosPreferences.list_states();
611 telemetry_state.latest_serial = AltosPreferences.latest_state();
613 telemetry_state.quiet = true;
615 AltosDebug.debug("latest serial %d\n", telemetry_state.latest_serial);
617 for (int serial : serials) {
618 AltosState saved_state = AltosPreferences.state(serial);
619 if (saved_state != null) {
620 AltosDebug.debug("recovered old state serial %d flight %d",
622 saved_state.cal_data().flight);
623 if (saved_state.gps != null)
624 AltosDebug.debug("\tposition %f,%f",
626 saved_state.gps.lon);
627 telemetry_state.put(serial, saved_state);
629 AltosDebug.debug("Failed to recover state for %d", serial);
630 AltosPreferences.remove_state(serial);
636 private String createNotificationChannel(String channelId, String channelName) {
637 NotificationChannel chan = new NotificationChannel(
638 channelId, channelName, NotificationManager.IMPORTANCE_NONE);
639 chan.setLightColor(Color.BLUE);
640 chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
641 NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
642 service.createNotificationChannel(chan);
647 public int onStartCommand(Intent intent, int flags, int startId) {
648 AltosDebug.debug("Received start id %d: %s", startId, intent);
650 // The PendingIntent to launch our activity if the user selects this notification
651 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
652 new Intent(this, AltosDroid.class), 0);
655 (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
656 ? createNotificationChannel("altosdroid_telemetry", "AltosDroid Telemetry Service")
659 // Create notification to be displayed while the service runs
660 Notification notification = new NotificationCompat.Builder(this, channelId)
661 .setContentTitle(getText(R.string.telemetry_service_label))
662 .setContentText(getText(R.string.telemetry_service_started))
663 .setContentIntent(contentIntent)
664 .setWhen(System.currentTimeMillis())
666 .setSmallIcon(R.drawable.am_status_c)
667 // .setLargeIcon(R.drawable.am_status_c)
670 // Move us into the foreground.
671 startForeground(NOTIFICATION, notification);
673 /* Start bluetooth if we don't have a connection already */
674 if (intent != null &&
675 (telemetry_state.connect == TelemetryState.CONNECT_NONE ||
676 telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED))
678 String action = intent.getAction();
680 if (action.equals(AltosDroid.ACTION_BLUETOOTH)) {
681 DeviceAddress address = AltosDroidPreferences.active_device();
682 if (address != null && !address.address.startsWith("USB"))
683 start_altos_bluetooth(address, false);
687 // We want this service to continue running until it is explicitly
688 // stopped, so return sticky.
693 public void onDestroy() {
695 // Stop the bluetooth Comms threads
698 // Demote us from the foreground, and cancel the persistent notification.
699 stopForeground(true);
701 // Tell the user we stopped.
702 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
706 public IBinder onBind(Intent intent) {
707 return messenger.getBinder();
710 /* AltosIdleMonitorListener */
711 public void update(AltosState state, AltosListenerState listener_state) {
713 AltosDebug.debug("update call %s freq %7.3f", state.cal_data().callsign, state.frequency);
714 telemetry_state.put(state.cal_data().serial, state);
715 telemetry_state.receiver_battery = listener_state.battery;
719 public void failed() {
722 public void error(String reason) {