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;
25 import android.app.Notification;
26 //import android.app.NotificationManager;
27 import android.app.PendingIntent;
28 import android.app.Service;
29 import android.bluetooth.BluetoothDevice;
30 import android.bluetooth.BluetoothAdapter;
31 import android.hardware.usb.*;
32 import android.content.Intent;
33 import android.content.Context;
34 import android.os.Bundle;
35 import android.os.IBinder;
36 import android.os.Handler;
37 import android.os.Message;
38 import android.os.Messenger;
39 import android.os.RemoteException;
40 import android.os.Looper;
41 import android.widget.Toast;
42 import android.location.Criteria;
44 import org.altusmetrum.altoslib_11.*;
46 public class TelemetryService extends Service implements AltosIdleMonitorListener {
48 static final int MSG_REGISTER_CLIENT = 1;
49 static final int MSG_UNREGISTER_CLIENT = 2;
50 static final int MSG_CONNECT = 3;
51 static final int MSG_OPEN_USB = 4;
52 static final int MSG_CONNECTED = 5;
53 static final int MSG_CONNECT_FAILED = 6;
54 static final int MSG_DISCONNECTED = 7;
55 static final int MSG_TELEMETRY = 8;
56 static final int MSG_SETFREQUENCY = 9;
57 static final int MSG_CRC_ERROR = 10;
58 static final int MSG_SETBAUD = 11;
59 static final int MSG_DISCONNECT = 12;
60 static final int MSG_DELETE_SERIAL = 13;
61 static final int MSG_BLUETOOTH_ENABLED = 14;
62 static final int MSG_MONITOR_IDLE_START= 15;
63 static final int MSG_MONITOR_IDLE_STOP = 16;
64 static final int MSG_REBOOT = 17;
65 static final int MSG_IGNITER_QUERY = 18;
66 static final int MSG_IGNITER_FIRE = 19;
68 // Unique Identification Number for the Notification.
69 // We use it on Notification start, and to cancel it.
70 private int NOTIFICATION = R.string.telemetry_service_label;
71 //private NotificationManager mNM;
73 ArrayList<Messenger> clients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
74 final Handler handler = new IncomingHandler(this);
75 final Messenger messenger = new Messenger(handler); // Target we publish for clients to send messages to IncomingHandler.
77 // Name of the connected device
78 DeviceAddress address;
79 private AltosDroidLink altos_link = null;
80 private TelemetryReader telemetry_reader = null;
81 private TelemetryLogger telemetry_logger = null;
83 // Local Bluetooth adapter
84 private BluetoothAdapter bluetooth_adapter = null;
86 // Last data seen; send to UI when it starts
87 private TelemetryState telemetry_state;
89 // Idle monitor if active
90 AltosIdleMonitor idle_monitor = null;
93 AltosIgnite ignite = null;
94 boolean ignite_running;
96 // Handler of incoming messages from clients.
97 static class IncomingHandler extends Handler {
98 private final WeakReference<TelemetryService> service;
99 IncomingHandler(TelemetryService s) { service = new WeakReference<TelemetryService>(s); }
102 public void handleMessage(Message msg) {
103 DeviceAddress address;
105 TelemetryService s = service.get();
106 AltosDroidLink bt = null;
112 /* Messages from application */
113 case MSG_REGISTER_CLIENT:
114 s.add_client(msg.replyTo);
116 case MSG_UNREGISTER_CLIENT:
117 s.remove_client(msg.replyTo);
120 AltosDebug.debug("Connect command received");
121 address = (DeviceAddress) msg.obj;
122 AltosDroidPreferences.set_active_device(address);
123 s.start_altos_bluetooth(address, false);
126 AltosDebug.debug("Open USB command received");
127 UsbDevice device = (UsbDevice) msg.obj;
131 AltosDebug.debug("Disconnect command received");
133 if (!(Boolean) msg.obj)
134 AltosDroidPreferences.set_active_device(null);
137 case MSG_DELETE_SERIAL:
138 AltosDebug.debug("Delete Serial command received");
139 s.delete_serial((Integer) msg.obj);
141 case MSG_SETFREQUENCY:
142 AltosDebug.debug("MSG_SETFREQUENCY");
143 s.telemetry_state.frequency = (Double) msg.obj;
144 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
146 s.altos_link.set_radio_frequency(s.telemetry_state.frequency);
147 s.altos_link.save_frequency();
148 } catch (InterruptedException e) {
149 } catch (TimeoutException e) {
155 AltosDebug.debug("MSG_SETBAUD");
156 s.telemetry_state.telemetry_rate = (Integer) msg.obj;
157 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
158 s.altos_link.set_telemetry_rate(s.telemetry_state.telemetry_rate);
159 s.altos_link.save_telemetry_rate();
165 *Messages from AltosBluetooth
168 AltosDebug.debug("MSG_CONNECTED");
169 bt = (AltosDroidLink) msg.obj;
171 if (bt != s.altos_link) {
172 AltosDebug.debug("Stale message");
175 AltosDebug.debug("Connected to device");
178 } catch (InterruptedException ie) {
181 case MSG_CONNECT_FAILED:
182 AltosDebug.debug("MSG_CONNECT_FAILED");
183 bt = (AltosDroidLink) msg.obj;
185 if (bt != s.altos_link) {
186 AltosDebug.debug("Stale message");
189 if (s.address != null) {
190 AltosDebug.debug("Connection failed... retrying");
191 s.start_altos_bluetooth(s.address, true);
196 case MSG_DISCONNECTED:
198 /* This can be sent by either AltosDroidLink or TelemetryReader */
199 AltosDebug.debug("MSG_DISCONNECTED");
200 bt = (AltosDroidLink) msg.obj;
202 if (bt != s.altos_link) {
203 AltosDebug.debug("Stale message");
206 if (s.address != null) {
207 AltosDebug.debug("Connection lost... retrying");
208 s.start_altos_bluetooth(s.address, true);
215 * Messages from TelemetryReader
218 s.telemetry((AltosTelemetry) msg.obj);
221 // forward crc error messages
222 s.telemetry_state.crc_errors = (Integer) msg.obj;
225 case MSG_BLUETOOTH_ENABLED:
226 AltosDebug.debug("TelemetryService notes that BT is now enabled");
227 address = AltosDroidPreferences.active_device();
228 if (address != null && !address.address.startsWith("USB"))
229 s.start_altos_bluetooth(address, false);
231 case MSG_MONITOR_IDLE_START:
232 AltosDebug.debug("start monitor idle");
233 s.start_idle_monitor();
235 case MSG_MONITOR_IDLE_STOP:
236 AltosDebug.debug("stop monitor idle");
237 s.stop_idle_monitor();
240 AltosDebug.debug("reboot");
243 case MSG_IGNITER_QUERY:
244 AltosDebug.debug("igniter query");
245 s.igniter_query(msg.replyTo);
247 case MSG_IGNITER_FIRE:
248 AltosDebug.debug("igniter fire");
249 s.igniter_fire((String) msg.obj);
252 super.handleMessage(msg);
257 /* Handle telemetry packet
259 private void telemetry(AltosTelemetry telem) {
262 if (telemetry_state.states.containsKey(telem.serial))
263 state = telemetry_state.states.get(telem.serial).clone();
265 state = new AltosState();
266 telem.update_state(state);
267 telemetry_state.states.put(telem.serial, state);
269 AltosPreferences.set_state(state);
274 /* Construct the message to deliver to clients
276 private Message message() {
277 if (telemetry_state == null)
278 AltosDebug.debug("telemetry_state null!");
279 if (telemetry_state.states == null)
280 AltosDebug.debug("telemetry_state.states null!");
281 return Message.obtain(null, AltosDroid.MSG_STATE, telemetry_state);
284 /* A new friend has connected
286 private void add_client(Messenger client) {
289 AltosDebug.debug("Client bound to service");
291 /* On connect, send the current state to the new client
293 send_to_client(client);
294 send_idle_mode_to_client(client);
296 /* If we've got an address from a previous session, then
297 * go ahead and try to reconnect to the device
299 if (address != null && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
300 AltosDebug.debug("Reconnecting now...");
301 start_altos_bluetooth(address, false);
305 /* A client has disconnected, clean up
307 private void remove_client(Messenger client) {
308 clients.remove(client);
309 AltosDebug.debug("Client unbound from service");
311 /* When the list of clients is empty, stop the service if
312 * we have no current telemetry source
315 if (clients.isEmpty() && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
316 AltosDebug.debug("No clients, no connection. Stopping\n");
321 private void send_to_client(Messenger client) {
322 Message m = message();
325 } catch (RemoteException e) {
326 AltosDebug.error("Client %s disappeared", client.toString());
327 remove_client(client);
331 private void send_to_clients() {
332 for (Messenger client : clients)
333 send_to_client(client);
336 private void send_idle_mode_to_client(Messenger client) {
337 Message m = Message.obtain(null, AltosDroid.MSG_IDLE_MODE, idle_monitor != null);
340 } catch (RemoteException e) {
341 AltosDebug.error("Client %s disappeared", client.toString());
342 remove_client(client);
346 private void send_idle_mode_to_clients() {
347 for (Messenger client : clients)
348 send_idle_mode_to_client(client);
351 private void telemetry_start() {
352 if (telemetry_reader == null && idle_monitor == null && !ignite_running) {
353 telemetry_reader = new TelemetryReader(altos_link, handler);
354 telemetry_reader.start();
358 private void telemetry_stop() {
359 if (telemetry_reader != null) {
360 AltosDebug.debug("disconnect(): stopping TelemetryReader");
361 telemetry_reader.interrupt();
363 telemetry_reader.join();
364 } catch (InterruptedException e) {
366 telemetry_reader = null;
370 private void disconnect(boolean notify) {
371 AltosDebug.debug("disconnect(): begin");
373 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
374 telemetry_state.address = null;
376 if (idle_monitor != null)
379 if (altos_link != null)
380 altos_link.closing();
382 stop_receiver_voltage_timer();
385 if (telemetry_logger != null) {
386 AltosDebug.debug("disconnect(): stopping TelemetryLogger");
387 telemetry_logger.stop();
388 telemetry_logger = null;
390 if (altos_link != null) {
391 AltosDebug.debug("disconnect(): stopping AltosDroidLink");
396 telemetry_state.config = null;
398 AltosDebug.debug("disconnect(): send message to clients");
400 if (clients.isEmpty()) {
401 AltosDebug.debug("disconnect(): no clients, terminating");
407 private void start_usb(UsbDevice device) {
408 AltosUsb d = new AltosUsb(this, device, handler);
415 } catch (InterruptedException ie) {
420 private void delete_serial(int serial) {
421 telemetry_state.states.remove((Integer) serial);
422 AltosPreferences.remove_state(serial);
426 private void start_altos_bluetooth(DeviceAddress address, boolean pause) {
427 if (bluetooth_adapter == null || !bluetooth_adapter.isEnabled())
432 // Get the BluetoothDevice object
433 BluetoothDevice device = bluetooth_adapter.getRemoteDevice(address.address);
435 this.address = address;
436 AltosDebug.debug("start_altos_bluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress());
437 altos_link = new AltosBluetooth(device, handler, pause);
438 telemetry_state.connect = TelemetryState.CONNECT_CONNECTING;
439 telemetry_state.address = address;
443 private void start_idle_monitor() {
444 if (altos_link != null && idle_monitor == null) {
446 idle_monitor = new AltosIdleMonitor(this, altos_link, true, false);
447 idle_monitor.set_callsign(AltosPreferences.callsign());
448 idle_monitor.start();
449 send_idle_mode_to_clients();
453 private void stop_idle_monitor() {
454 if (idle_monitor != null) {
456 idle_monitor.abort();
457 } catch (InterruptedException ie) {
461 send_idle_mode_to_clients();
465 private void reboot_remote() {
466 if (altos_link != null) {
469 altos_link.start_remote();
470 altos_link.printf("r eboot\n");
471 altos_link.flush_output();
472 } catch (TimeoutException te) {
473 } catch (InterruptedException ie) {
476 altos_link.stop_remote();
477 } catch (InterruptedException ie) {
483 private void ensure_ignite() {
485 ignite = new AltosIgnite(altos_link, true, false);
488 private synchronized void igniter_query(Messenger client) {
490 HashMap<String,Integer> status_map = null;
491 ignite_running = true;
495 status_map = ignite.status();
496 } catch (InterruptedException ie) {
497 AltosDebug.debug("ignite.status interrupted");
498 } catch (TimeoutException te) {
499 AltosDebug.debug("ignite.status timeout");
502 ignite_running = false;
504 Message m = Message.obtain(null, AltosDroid.MSG_IGNITER_STATUS, status_map);
507 } catch (RemoteException e) {
511 private synchronized void igniter_fire(String igniter) {
513 ignite_running = true;
516 ignite.fire(igniter);
517 } catch (InterruptedException ie) {
519 ignite_running = false;
523 // Timer for receiver battery voltage monitoring
524 Timer receiver_voltage_timer;
526 private void update_receiver_voltage() {
527 if (altos_link != null && idle_monitor == null && !ignite_running) {
529 double voltage = altos_link.monitor_battery();
530 telemetry_state.receiver_battery = voltage;
532 } catch (InterruptedException ie) {
537 private void stop_receiver_voltage_timer() {
538 if (receiver_voltage_timer != null) {
539 receiver_voltage_timer.cancel();
540 receiver_voltage_timer.purge();
541 receiver_voltage_timer = null;
545 private void start_receiver_voltage_timer() {
546 if (receiver_voltage_timer == null && altos_link.has_monitor_battery()) {
547 receiver_voltage_timer = new Timer();
548 receiver_voltage_timer.scheduleAtFixedRate(new TimerTask() { public void run() {update_receiver_voltage();}}, 1000L, 10000L);
552 private void connected() throws InterruptedException {
553 AltosDebug.debug("connected top");
554 AltosDebug.check_ui("connected\n");
556 if (altos_link == null)
557 throw new InterruptedException("no bluetooth");
558 telemetry_state.config = altos_link.config_data();
559 altos_link.set_radio_frequency(telemetry_state.frequency);
560 altos_link.set_telemetry_rate(telemetry_state.telemetry_rate);
561 } catch (TimeoutException e) {
562 // If this timed out, then we really want to retry it, but
563 // probably safer to just retry the connection from scratch.
564 AltosDebug.debug("connected timeout");
565 if (address != null) {
566 AltosDebug.debug("connected timeout, retrying");
567 start_altos_bluetooth(address, true);
569 handler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
575 AltosDebug.debug("connected bluetooth configured");
576 telemetry_state.connect = TelemetryState.CONNECT_CONNECTED;
577 telemetry_state.address = address;
581 AltosDebug.debug("connected TelemetryReader started");
583 telemetry_logger = new TelemetryLogger(this, altos_link);
585 start_receiver_voltage_timer();
587 AltosDebug.debug("Notify UI of connection");
594 public void onCreate() {
596 AltosDebug.init(this);
598 // Initialise preferences
599 AltosDroidPreferences.init(this);
601 // Get local Bluetooth adapter
602 bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
604 telemetry_state = new TelemetryState();
606 // Create a reference to the NotificationManager so that we can update our notifcation text later
607 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
609 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
610 telemetry_state.address = null;
612 /* Pull the saved state information out of the preferences database
614 ArrayList<Integer> serials = AltosPreferences.list_states();
616 telemetry_state.latest_serial = AltosPreferences.latest_state();
618 AltosDebug.debug("latest serial %d\n", telemetry_state.latest_serial);
620 for (int serial : serials) {
621 AltosState saved_state = AltosPreferences.state(serial);
622 if (saved_state != null) {
623 if (telemetry_state.latest_serial == 0)
624 telemetry_state.latest_serial = serial;
626 AltosDebug.debug("recovered old state serial %d flight %d",
629 if (saved_state.gps != null)
630 AltosDebug.debug("\tposition %f,%f",
632 saved_state.gps.lon);
633 telemetry_state.states.put(serial, saved_state);
635 AltosDebug.debug("Failed to recover state for %d", serial);
636 AltosPreferences.remove_state(serial);
642 public int onStartCommand(Intent intent, int flags, int startId) {
643 AltosDebug.debug("Received start id %d: %s", startId, intent);
645 CharSequence text = getText(R.string.telemetry_service_started);
647 // Create notification to be displayed while the service runs
648 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
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);
654 // Set the info for the views that show in the notification panel.
655 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
657 // Set the notification to be in the "Ongoing" section.
658 notification.flags |= Notification.FLAG_ONGOING_EVENT;
660 // Move us into the foreground.
661 startForeground(NOTIFICATION, notification);
663 /* Start bluetooth if we don't have a connection already */
664 if (intent != null &&
665 (telemetry_state.connect == TelemetryState.CONNECT_NONE ||
666 telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED))
668 String action = intent.getAction();
670 if (action.equals(AltosDroid.ACTION_BLUETOOTH)) {
671 DeviceAddress address = AltosDroidPreferences.active_device();
672 if (address != null && !address.address.startsWith("USB"))
673 start_altos_bluetooth(address, false);
677 // We want this service to continue running until it is explicitly
678 // stopped, so return sticky.
683 public void onDestroy() {
685 // Stop the bluetooth Comms threads
688 // Demote us from the foreground, and cancel the persistent notification.
689 stopForeground(true);
691 // Tell the user we stopped.
692 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
696 public IBinder onBind(Intent intent) {
697 return messenger.getBinder();
700 /* AltosIdleMonitorListener */
701 public void update(AltosState state, AltosListenerState listener_state) {
702 telemetry_state.states.put(state.serial, state);
703 telemetry_state.receiver_battery = listener_state.battery;
707 public void failed() {
710 public void error(String reason) {