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_13.*;
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.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
138 s.altos_link.set_radio_frequency(s.telemetry_state.frequency);
139 s.altos_link.save_frequency();
140 } catch (InterruptedException e) {
141 } catch (TimeoutException e) {
147 AltosDebug.debug("MSG_SETBAUD");
148 s.telemetry_state.telemetry_rate = (Integer) msg.obj;
149 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
150 s.altos_link.set_telemetry_rate(s.telemetry_state.telemetry_rate);
151 s.altos_link.save_telemetry_rate();
157 *Messages from AltosBluetooth
160 AltosDebug.debug("MSG_CONNECTED");
161 bt = (AltosDroidLink) msg.obj;
163 if (bt != s.altos_link) {
164 AltosDebug.debug("Stale message");
167 AltosDebug.debug("Connected to device");
170 } catch (InterruptedException ie) {
173 case MSG_CONNECT_FAILED:
174 AltosDebug.debug("MSG_CONNECT_FAILED");
175 bt = (AltosDroidLink) msg.obj;
177 if (bt != s.altos_link) {
178 AltosDebug.debug("Stale message");
181 if (s.address != null) {
182 AltosDebug.debug("Connection failed... retrying");
183 s.start_altos_bluetooth(s.address, true);
188 case MSG_DISCONNECTED:
190 /* This can be sent by either AltosDroidLink or TelemetryReader */
191 AltosDebug.debug("MSG_DISCONNECTED");
192 bt = (AltosDroidLink) msg.obj;
194 if (bt != s.altos_link) {
195 AltosDebug.debug("Stale message");
198 if (s.address != null) {
199 AltosDebug.debug("Connection lost... retrying");
200 s.start_altos_bluetooth(s.address, true);
207 * Messages from TelemetryReader
210 s.telemetry((AltosTelemetry) msg.obj);
213 // forward crc error messages
214 s.telemetry_state.crc_errors = (Integer) msg.obj;
217 case MSG_BLUETOOTH_ENABLED:
218 AltosDebug.debug("TelemetryService notes that BT is now enabled");
219 address = AltosDroidPreferences.active_device();
220 if (address != null && !address.address.startsWith("USB"))
221 s.start_altos_bluetooth(address, false);
223 case MSG_MONITOR_IDLE_START:
224 AltosDebug.debug("start monitor idle");
225 s.start_idle_monitor();
227 case MSG_MONITOR_IDLE_STOP:
228 AltosDebug.debug("stop monitor idle");
229 s.stop_idle_monitor();
232 AltosDebug.debug("reboot");
235 case MSG_IGNITER_QUERY:
236 AltosDebug.debug("igniter query");
237 s.igniter_query(msg.replyTo);
239 case MSG_IGNITER_FIRE:
240 AltosDebug.debug("igniter fire");
241 s.igniter_fire((String) msg.obj);
244 super.handleMessage(msg);
249 /* Handle telemetry packet
251 private void telemetry(AltosTelemetry telem) {
254 if (telemetry_state.states.containsKey(telem.serial()))
255 state = telemetry_state.states.get(telem.serial());
257 state = new AltosState(new AltosCalData());
258 telem.provide_data(state);
259 telemetry_state.states.put(telem.serial(), state);
260 telemetry_state.quiet = false;
262 AltosPreferences.set_state(state,telem.serial());
267 /* Construct the message to deliver to clients
269 private Message message() {
270 if (telemetry_state == null)
271 AltosDebug.debug("telemetry_state null!");
272 if (telemetry_state.states == null)
273 AltosDebug.debug("telemetry_state.states 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 telemetry_start() {
345 if (telemetry_reader == null && idle_monitor == null && !ignite_running) {
346 telemetry_reader = new TelemetryReader(altos_link, handler);
347 telemetry_reader.start();
351 private void telemetry_stop() {
352 if (telemetry_reader != null) {
353 AltosDebug.debug("disconnect(): stopping TelemetryReader");
354 telemetry_reader.interrupt();
356 telemetry_reader.join();
357 } catch (InterruptedException e) {
359 telemetry_reader = null;
363 private void disconnect(boolean notify) {
364 AltosDebug.debug("disconnect(): begin");
366 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
367 telemetry_state.address = null;
369 if (idle_monitor != null)
372 if (altos_link != null)
373 altos_link.closing();
375 stop_receiver_voltage_timer();
378 if (telemetry_logger != null) {
379 AltosDebug.debug("disconnect(): stopping TelemetryLogger");
380 telemetry_logger.stop();
381 telemetry_logger = null;
383 if (altos_link != null) {
384 AltosDebug.debug("disconnect(): stopping AltosDroidLink");
389 telemetry_state.config = null;
391 AltosDebug.debug("disconnect(): send message to clients");
393 if (clients.isEmpty()) {
394 AltosDebug.debug("disconnect(): no clients, terminating");
400 private void start_usb(UsbDevice device) {
401 AltosUsb d = new AltosUsb(this, device, handler);
408 } catch (InterruptedException ie) {
413 private void delete_serial(int serial) {
414 telemetry_state.states.remove((Integer) serial);
415 AltosPreferences.remove_state(serial);
419 private void start_altos_bluetooth(DeviceAddress address, boolean pause) {
420 if (bluetooth_adapter == null || !bluetooth_adapter.isEnabled())
425 // Get the BluetoothDevice object
426 BluetoothDevice device = bluetooth_adapter.getRemoteDevice(address.address);
428 this.address = address;
429 AltosDebug.debug("start_altos_bluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress());
430 altos_link = new AltosBluetooth(device, handler, pause);
431 telemetry_state.connect = TelemetryState.CONNECT_CONNECTING;
432 telemetry_state.address = address;
436 private void start_idle_monitor() {
437 if (altos_link != null && idle_monitor == null) {
439 idle_monitor = new AltosIdleMonitor(this, altos_link, true, false);
440 idle_monitor.set_callsign(AltosPreferences.callsign());
441 idle_monitor.start();
442 send_idle_mode_to_clients();
446 private void stop_idle_monitor() {
447 if (idle_monitor != null) {
449 idle_monitor.abort();
450 } catch (InterruptedException ie) {
454 send_idle_mode_to_clients();
458 private void reboot_remote() {
459 if (altos_link != null) {
462 altos_link.start_remote();
463 altos_link.printf("r eboot\n");
464 altos_link.flush_output();
465 } catch (TimeoutException te) {
466 } catch (InterruptedException ie) {
469 altos_link.stop_remote();
470 } catch (InterruptedException ie) {
476 private void ensure_ignite() {
478 ignite = new AltosIgnite(altos_link, true, false);
481 private synchronized void igniter_query(Messenger client) {
483 HashMap<String,Integer> status_map = null;
484 ignite_running = true;
488 status_map = ignite.status();
489 } catch (InterruptedException ie) {
490 AltosDebug.debug("ignite.status interrupted");
491 } catch (TimeoutException te) {
492 AltosDebug.debug("ignite.status timeout");
495 ignite_running = false;
497 Message m = Message.obtain(null, AltosDroid.MSG_IGNITER_STATUS, status_map);
500 } catch (RemoteException e) {
504 private synchronized void igniter_fire(String igniter) {
506 ignite_running = true;
509 ignite.fire(igniter);
510 } catch (InterruptedException ie) {
512 ignite_running = false;
516 // Timer for receiver battery voltage monitoring
517 Timer receiver_voltage_timer;
519 private void update_receiver_voltage() {
520 if (altos_link != null && idle_monitor == null && !ignite_running) {
522 double voltage = altos_link.monitor_battery();
523 telemetry_state.receiver_battery = voltage;
525 } catch (InterruptedException ie) {
530 private void stop_receiver_voltage_timer() {
531 if (receiver_voltage_timer != null) {
532 receiver_voltage_timer.cancel();
533 receiver_voltage_timer.purge();
534 receiver_voltage_timer = null;
538 private void start_receiver_voltage_timer() {
539 if (receiver_voltage_timer == null && altos_link.has_monitor_battery()) {
540 receiver_voltage_timer = new Timer();
541 receiver_voltage_timer.scheduleAtFixedRate(new TimerTask() { public void run() {update_receiver_voltage();}}, 1000L, 10000L);
545 private void connected() throws InterruptedException {
546 AltosDebug.debug("connected top");
547 AltosDebug.check_ui("connected\n");
549 if (altos_link == null)
550 throw new InterruptedException("no bluetooth");
551 telemetry_state.config = altos_link.config_data();
552 altos_link.set_radio_frequency(telemetry_state.frequency);
553 altos_link.set_telemetry_rate(telemetry_state.telemetry_rate);
554 } catch (TimeoutException e) {
555 // If this timed out, then we really want to retry it, but
556 // probably safer to just retry the connection from scratch.
557 AltosDebug.debug("connected timeout");
558 if (address != null) {
559 AltosDebug.debug("connected timeout, retrying");
560 start_altos_bluetooth(address, true);
562 handler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
568 AltosDebug.debug("connected bluetooth configured");
569 telemetry_state.connect = TelemetryState.CONNECT_CONNECTED;
570 telemetry_state.address = address;
574 AltosDebug.debug("connected TelemetryReader started");
576 telemetry_logger = new TelemetryLogger(this, altos_link);
578 start_receiver_voltage_timer();
580 AltosDebug.debug("Notify UI of connection");
587 public void onCreate() {
589 AltosDebug.init(this);
591 // Initialise preferences
592 AltosDroidPreferences.init(this);
594 // Get local Bluetooth adapter
595 bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
597 telemetry_state = new TelemetryState();
599 // Create a reference to the NotificationManager so that we can update our notifcation text later
600 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
602 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
603 telemetry_state.address = null;
605 /* Pull the saved state information out of the preferences database
607 ArrayList<Integer> serials = AltosPreferences.list_states();
609 telemetry_state.latest_serial = AltosPreferences.latest_state();
611 telemetry_state.quiet = true;
613 AltosDebug.debug("latest serial %d\n", telemetry_state.latest_serial);
615 for (int serial : serials) {
616 AltosState saved_state = AltosPreferences.state(serial);
617 if (saved_state != null) {
618 if (telemetry_state.latest_serial == 0)
619 telemetry_state.latest_serial = serial;
621 AltosDebug.debug("recovered old state serial %d flight %d",
623 saved_state.cal_data().flight);
624 if (saved_state.gps != null)
625 AltosDebug.debug("\tposition %f,%f",
627 saved_state.gps.lon);
628 telemetry_state.states.put(serial, saved_state);
630 AltosDebug.debug("Failed to recover state for %d", serial);
631 AltosPreferences.remove_state(serial);
637 private String createNotificationChannel(String channelId, String channelName) {
638 NotificationChannel chan = new NotificationChannel(
639 channelId, channelName, NotificationManager.IMPORTANCE_NONE);
640 chan.setLightColor(Color.BLUE);
641 chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
642 NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
643 service.createNotificationChannel(chan);
648 public int onStartCommand(Intent intent, int flags, int startId) {
649 AltosDebug.debug("Received start id %d: %s", startId, intent);
651 // The PendingIntent to launch our activity if the user selects this notification
652 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
653 new Intent(this, AltosDroid.class), 0);
656 (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
657 ? createNotificationChannel("altosdroid_telemetry", "AltosDroid Telemetry Service")
660 // Create notification to be displayed while the service runs
661 Notification notification = new NotificationCompat.Builder(this, channelId)
662 .setContentTitle(getText(R.string.telemetry_service_label))
663 .setContentText(getText(R.string.telemetry_service_started))
664 .setContentIntent(contentIntent)
665 .setWhen(System.currentTimeMillis())
667 .setSmallIcon(R.drawable.am_status_c)
668 // .setLargeIcon(R.drawable.am_status_c)
671 // Move us into the foreground.
672 startForeground(NOTIFICATION, notification);
674 /* Start bluetooth if we don't have a connection already */
675 if (intent != null &&
676 (telemetry_state.connect == TelemetryState.CONNECT_NONE ||
677 telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED))
679 String action = intent.getAction();
681 if (action.equals(AltosDroid.ACTION_BLUETOOTH)) {
682 DeviceAddress address = AltosDroidPreferences.active_device();
683 if (address != null && !address.address.startsWith("USB"))
684 start_altos_bluetooth(address, false);
688 // We want this service to continue running until it is explicitly
689 // stopped, so return sticky.
694 public void onDestroy() {
696 // Stop the bluetooth Comms threads
699 // Demote us from the foreground, and cancel the persistent notification.
700 stopForeground(true);
702 // Tell the user we stopped.
703 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
707 public IBinder onBind(Intent intent) {
708 return messenger.getBinder();
711 /* AltosIdleMonitorListener */
712 public void update(AltosState state, AltosListenerState listener_state) {
713 telemetry_state.states.put(state.cal_data().serial, state);
714 telemetry_state.receiver_battery = listener_state.battery;
718 public void failed() {
721 public void error(String reason) {