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 state = telemetry_state.get(telem.serial());
256 state = new AltosState(new AltosCalData());
257 telem.provide_data(state);
258 telemetry_state.put(telem.serial(), state);
259 telemetry_state.quiet = false;
261 AltosPreferences.set_state(state,telem.serial());
266 /* Construct the message to deliver to clients
268 private Message message() {
269 if (telemetry_state == null)
270 AltosDebug.debug("telemetry_state null!");
271 return Message.obtain(null, AltosDroid.MSG_STATE, telemetry_state);
274 /* A new friend has connected
276 private void add_client(Messenger client) {
279 AltosDebug.debug("Client bound to service");
281 /* On connect, send the current state to the new client
283 send_to_client(client);
284 send_idle_mode_to_client(client);
286 /* If we've got an address from a previous session, then
287 * go ahead and try to reconnect to the device
289 if (address != null && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
290 AltosDebug.debug("Reconnecting now...");
291 start_altos_bluetooth(address, false);
295 /* A client has disconnected, clean up
297 private void remove_client(Messenger client) {
298 clients.remove(client);
299 AltosDebug.debug("Client unbound from service");
301 /* When the list of clients is empty, stop the service if
302 * we have no current telemetry source
305 if (clients.isEmpty() && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
306 AltosDebug.debug("No clients, no connection. Stopping\n");
311 private void send_to_client(Messenger client) {
312 Message m = message();
315 } catch (RemoteException e) {
316 AltosDebug.error("Client %s disappeared", client.toString());
317 remove_client(client);
321 private void send_to_clients() {
322 for (Messenger client : clients)
323 send_to_client(client);
326 private void send_idle_mode_to_client(Messenger client) {
327 Message m = Message.obtain(null, AltosDroid.MSG_IDLE_MODE, idle_monitor != null);
330 } catch (RemoteException e) {
331 AltosDebug.error("Client %s disappeared", client.toString());
332 remove_client(client);
336 private void send_idle_mode_to_clients() {
337 for (Messenger client : clients)
338 send_idle_mode_to_client(client);
341 private void telemetry_start() {
342 if (telemetry_reader == null && idle_monitor == null && !ignite_running) {
343 telemetry_reader = new TelemetryReader(altos_link, handler);
344 telemetry_reader.start();
348 private void telemetry_stop() {
349 if (telemetry_reader != null) {
350 AltosDebug.debug("disconnect(): stopping TelemetryReader");
351 telemetry_reader.interrupt();
353 telemetry_reader.join();
354 } catch (InterruptedException e) {
356 telemetry_reader = null;
360 private void disconnect(boolean notify) {
361 AltosDebug.debug("disconnect(): begin");
363 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
364 telemetry_state.address = null;
366 if (idle_monitor != null)
369 if (altos_link != null)
370 altos_link.closing();
372 stop_receiver_voltage_timer();
375 if (telemetry_logger != null) {
376 AltosDebug.debug("disconnect(): stopping TelemetryLogger");
377 telemetry_logger.stop();
378 telemetry_logger = null;
380 if (altos_link != null) {
381 AltosDebug.debug("disconnect(): stopping AltosDroidLink");
386 telemetry_state.config = null;
388 AltosDebug.debug("disconnect(): send message to clients");
390 if (clients.isEmpty()) {
391 AltosDebug.debug("disconnect(): no clients, terminating");
397 private void start_usb(UsbDevice device) {
398 AltosUsb d = new AltosUsb(this, device, handler);
405 } catch (InterruptedException ie) {
410 private void delete_serial(int serial) {
411 telemetry_state.remove(serial);
412 AltosPreferences.remove_state(serial);
416 private void start_altos_bluetooth(DeviceAddress address, boolean pause) {
417 if (bluetooth_adapter == null || !bluetooth_adapter.isEnabled())
422 // Get the BluetoothDevice object
423 BluetoothDevice device = bluetooth_adapter.getRemoteDevice(address.address);
425 this.address = address;
426 AltosDebug.debug("start_altos_bluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress());
427 altos_link = new AltosBluetooth(device, handler, pause);
428 telemetry_state.connect = TelemetryState.CONNECT_CONNECTING;
429 telemetry_state.address = address;
433 private void start_idle_monitor() {
434 if (altos_link != null && idle_monitor == null) {
436 idle_monitor = new AltosIdleMonitor(this, altos_link, true, false);
437 idle_monitor.set_callsign(AltosPreferences.callsign());
438 idle_monitor.set_frequency(telemetry_state.frequency);
439 telemetry_state.idle_mode = true;
440 idle_monitor.start();
441 send_idle_mode_to_clients();
445 private void stop_idle_monitor() {
446 if (idle_monitor != null) {
448 idle_monitor.abort();
449 } catch (InterruptedException ie) {
452 telemetry_state.idle_mode = false;
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 AltosDebug.debug("recovered old state serial %d flight %d",
620 saved_state.cal_data().flight);
621 if (saved_state.gps != null)
622 AltosDebug.debug("\tposition %f,%f",
624 saved_state.gps.lon);
625 telemetry_state.put(serial, saved_state);
627 AltosDebug.debug("Failed to recover state for %d", serial);
628 AltosPreferences.remove_state(serial);
634 private String createNotificationChannel(String channelId, String channelName) {
635 NotificationChannel chan = new NotificationChannel(
636 channelId, channelName, NotificationManager.IMPORTANCE_NONE);
637 chan.setLightColor(Color.BLUE);
638 chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
639 NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
640 service.createNotificationChannel(chan);
645 public int onStartCommand(Intent intent, int flags, int startId) {
646 AltosDebug.debug("Received start id %d: %s", startId, intent);
648 // The PendingIntent to launch our activity if the user selects this notification
649 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
650 new Intent(this, AltosDroid.class), 0);
653 (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
654 ? createNotificationChannel("altosdroid_telemetry", "AltosDroid Telemetry Service")
657 // Create notification to be displayed while the service runs
658 Notification notification = new NotificationCompat.Builder(this, channelId)
659 .setContentTitle(getText(R.string.telemetry_service_label))
660 .setContentText(getText(R.string.telemetry_service_started))
661 .setContentIntent(contentIntent)
662 .setWhen(System.currentTimeMillis())
664 .setSmallIcon(R.drawable.am_status_c)
665 // .setLargeIcon(R.drawable.am_status_c)
668 // Move us into the foreground.
669 startForeground(NOTIFICATION, notification);
671 /* Start bluetooth if we don't have a connection already */
672 if (intent != null &&
673 (telemetry_state.connect == TelemetryState.CONNECT_NONE ||
674 telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED))
676 String action = intent.getAction();
678 if (action.equals(AltosDroid.ACTION_BLUETOOTH)) {
679 DeviceAddress address = AltosDroidPreferences.active_device();
680 if (address != null && !address.address.startsWith("USB"))
681 start_altos_bluetooth(address, false);
685 // We want this service to continue running until it is explicitly
686 // stopped, so return sticky.
691 public void onDestroy() {
693 // Stop the bluetooth Comms threads
696 // Demote us from the foreground, and cancel the persistent notification.
697 stopForeground(true);
699 // Tell the user we stopped.
700 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
704 public IBinder onBind(Intent intent) {
705 return messenger.getBinder();
708 /* AltosIdleMonitorListener */
709 public void update(AltosState state, AltosListenerState listener_state) {
711 AltosDebug.debug("update call %s freq %7.3f", state.cal_data().callsign, state.frequency);
712 telemetry_state.put(state.cal_data().serial, state);
713 telemetry_state.receiver_battery = listener_state.battery;
717 public void failed() {
720 public void error(String reason) {