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; version 2 of the License.
8 * This program is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
18 package org.altusmetrum.AltosDroid;
20 import java.lang.ref.WeakReference;
21 import java.util.concurrent.TimeoutException;
24 import android.app.Notification;
25 //import android.app.NotificationManager;
26 import android.app.PendingIntent;
27 import android.app.Service;
28 import android.bluetooth.BluetoothDevice;
29 import android.bluetooth.BluetoothAdapter;
30 import android.hardware.usb.*;
31 import android.content.Intent;
32 import android.content.Context;
33 import android.os.Bundle;
34 import android.os.IBinder;
35 import android.os.Handler;
36 import android.os.Message;
37 import android.os.Messenger;
38 import android.os.RemoteException;
39 import android.os.Looper;
40 import android.widget.Toast;
41 import android.location.Criteria;
43 import org.altusmetrum.altoslib_10.*;
45 public class TelemetryService extends Service implements AltosIdleMonitorListener {
47 static final int MSG_REGISTER_CLIENT = 1;
48 static final int MSG_UNREGISTER_CLIENT = 2;
49 static final int MSG_CONNECT = 3;
50 static final int MSG_OPEN_USB = 4;
51 static final int MSG_CONNECTED = 5;
52 static final int MSG_CONNECT_FAILED = 6;
53 static final int MSG_DISCONNECTED = 7;
54 static final int MSG_TELEMETRY = 8;
55 static final int MSG_SETFREQUENCY = 9;
56 static final int MSG_CRC_ERROR = 10;
57 static final int MSG_SETBAUD = 11;
58 static final int MSG_DISCONNECT = 12;
59 static final int MSG_DELETE_SERIAL = 13;
60 static final int MSG_BLUETOOTH_ENABLED = 14;
61 static final int MSG_MONITOR_IDLE_START= 15;
62 static final int MSG_MONITOR_IDLE_STOP = 16;
63 static final int MSG_REBOOT = 17;
64 static final int MSG_IGNITER_QUERY = 18;
65 static final int MSG_IGNITER_FIRE = 19;
67 // Unique Identification Number for the Notification.
68 // We use it on Notification start, and to cancel it.
69 private int NOTIFICATION = R.string.telemetry_service_label;
70 //private NotificationManager mNM;
72 ArrayList<Messenger> clients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
73 final Handler handler = new IncomingHandler(this);
74 final Messenger messenger = new Messenger(handler); // Target we publish for clients to send messages to IncomingHandler.
76 // Name of the connected device
77 DeviceAddress address;
78 private AltosDroidLink altos_link = null;
79 private TelemetryReader telemetry_reader = null;
80 private TelemetryLogger telemetry_logger = null;
82 // Local Bluetooth adapter
83 private BluetoothAdapter bluetooth_adapter = null;
85 // Last data seen; send to UI when it starts
86 private TelemetryState telemetry_state;
88 // Idle monitor if active
89 AltosIdleMonitor idle_monitor = null;
92 AltosIgnite ignite = null;
93 boolean ignite_running;
95 // Handler of incoming messages from clients.
96 static class IncomingHandler extends Handler {
97 private final WeakReference<TelemetryService> service;
98 IncomingHandler(TelemetryService s) { service = new WeakReference<TelemetryService>(s); }
101 public void handleMessage(Message msg) {
102 DeviceAddress address;
104 TelemetryService s = service.get();
105 AltosDroidLink bt = null;
111 /* Messages from application */
112 case MSG_REGISTER_CLIENT:
113 s.add_client(msg.replyTo);
115 case MSG_UNREGISTER_CLIENT:
116 s.remove_client(msg.replyTo);
119 AltosDebug.debug("Connect command received");
120 address = (DeviceAddress) msg.obj;
121 AltosDroidPreferences.set_active_device(address);
122 s.start_altos_bluetooth(address, false);
125 AltosDebug.debug("Open USB command received");
126 UsbDevice device = (UsbDevice) msg.obj;
130 AltosDebug.debug("Disconnect command received");
134 case MSG_DELETE_SERIAL:
135 AltosDebug.debug("Delete Serial command received");
136 s.delete_serial((Integer) msg.obj);
138 case MSG_SETFREQUENCY:
139 AltosDebug.debug("MSG_SETFREQUENCY");
140 s.telemetry_state.frequency = (Double) msg.obj;
141 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
143 s.altos_link.set_radio_frequency(s.telemetry_state.frequency);
144 s.altos_link.save_frequency();
145 } catch (InterruptedException e) {
146 } catch (TimeoutException e) {
152 AltosDebug.debug("MSG_SETBAUD");
153 s.telemetry_state.telemetry_rate = (Integer) msg.obj;
154 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
155 s.altos_link.set_telemetry_rate(s.telemetry_state.telemetry_rate);
156 s.altos_link.save_telemetry_rate();
162 *Messages from AltosBluetooth
165 AltosDebug.debug("MSG_CONNECTED");
166 bt = (AltosDroidLink) msg.obj;
168 if (bt != s.altos_link) {
169 AltosDebug.debug("Stale message");
172 AltosDebug.debug("Connected to device");
175 } catch (InterruptedException ie) {
178 case MSG_CONNECT_FAILED:
179 AltosDebug.debug("MSG_CONNECT_FAILED");
180 bt = (AltosDroidLink) msg.obj;
182 if (bt != s.altos_link) {
183 AltosDebug.debug("Stale message");
186 if (s.address != null) {
187 AltosDebug.debug("Connection failed... retrying");
188 s.start_altos_bluetooth(s.address, true);
193 case MSG_DISCONNECTED:
195 /* This can be sent by either AltosDroidLink or TelemetryReader */
196 AltosDebug.debug("MSG_DISCONNECTED");
197 bt = (AltosDroidLink) msg.obj;
199 if (bt != s.altos_link) {
200 AltosDebug.debug("Stale message");
203 if (s.address != null) {
204 AltosDebug.debug("Connection lost... retrying");
205 s.start_altos_bluetooth(s.address, true);
212 * Messages from TelemetryReader
215 s.telemetry((AltosTelemetry) msg.obj);
218 // forward crc error messages
219 s.telemetry_state.crc_errors = (Integer) msg.obj;
222 case MSG_BLUETOOTH_ENABLED:
223 AltosDebug.debug("TelemetryService notes that BT is now enabled");
224 address = AltosDroidPreferences.active_device();
225 if (address != null && !address.address.startsWith("USB"))
226 s.start_altos_bluetooth(address, false);
228 case MSG_MONITOR_IDLE_START:
229 AltosDebug.debug("start monitor idle");
230 s.start_idle_monitor();
232 case MSG_MONITOR_IDLE_STOP:
233 AltosDebug.debug("stop monitor idle");
234 s.stop_idle_monitor();
237 AltosDebug.debug("reboot");
240 case MSG_IGNITER_QUERY:
241 AltosDebug.debug("igniter query");
242 s.igniter_query(msg.replyTo);
244 case MSG_IGNITER_FIRE:
245 AltosDebug.debug("igniter fire");
246 s.igniter_fire((String) msg.obj);
249 super.handleMessage(msg);
254 /* Handle telemetry packet
256 private void telemetry(AltosTelemetry telem) {
259 if (telemetry_state.states.containsKey(telem.serial))
260 state = telemetry_state.states.get(telem.serial).clone();
262 state = new AltosState();
263 telem.update_state(state);
264 telemetry_state.states.put(telem.serial, state);
266 AltosPreferences.set_state(state);
271 /* Construct the message to deliver to clients
273 private Message message() {
274 if (telemetry_state == null)
275 AltosDebug.debug("telemetry_state null!");
276 if (telemetry_state.states == null)
277 AltosDebug.debug("telemetry_state.states null!");
278 return Message.obtain(null, AltosDroid.MSG_STATE, telemetry_state);
281 /* A new friend has connected
283 private void add_client(Messenger client) {
286 AltosDebug.debug("Client bound to service");
288 /* On connect, send the current state to the new client
290 send_to_client(client);
291 send_idle_mode_to_client(client);
293 /* If we've got an address from a previous session, then
294 * go ahead and try to reconnect to the device
296 if (address != null && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
297 AltosDebug.debug("Reconnecting now...");
298 start_altos_bluetooth(address, false);
302 /* A client has disconnected, clean up
304 private void remove_client(Messenger client) {
305 clients.remove(client);
306 AltosDebug.debug("Client unbound from service");
308 /* When the list of clients is empty, stop the service if
309 * we have no current telemetry source
312 if (clients.isEmpty() && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
313 AltosDebug.debug("No clients, no connection. Stopping\n");
318 private void send_to_client(Messenger client) {
319 Message m = message();
322 } catch (RemoteException e) {
323 AltosDebug.error("Client %s disappeared", client.toString());
324 remove_client(client);
328 private void send_to_clients() {
329 for (Messenger client : clients)
330 send_to_client(client);
333 private void send_idle_mode_to_client(Messenger client) {
334 Message m = Message.obtain(null, AltosDroid.MSG_IDLE_MODE, idle_monitor != null);
337 } catch (RemoteException e) {
338 AltosDebug.error("Client %s disappeared", client.toString());
339 remove_client(client);
343 private void send_idle_mode_to_clients() {
344 for (Messenger client : clients)
345 send_idle_mode_to_client(client);
348 private void telemetry_start() {
349 if (telemetry_reader == null && idle_monitor == null && !ignite_running) {
350 telemetry_reader = new TelemetryReader(altos_link, handler);
351 telemetry_reader.start();
355 private void telemetry_stop() {
356 if (telemetry_reader != null) {
357 AltosDebug.debug("disconnect(): stopping TelemetryReader");
358 telemetry_reader.interrupt();
360 telemetry_reader.join();
361 } catch (InterruptedException e) {
363 telemetry_reader = null;
367 private void disconnect(boolean notify) {
368 AltosDebug.debug("disconnect(): begin");
370 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
371 telemetry_state.address = null;
373 if (idle_monitor != null)
376 if (altos_link != null)
377 altos_link.closing();
379 stop_receiver_voltage_timer();
382 if (telemetry_logger != null) {
383 AltosDebug.debug("disconnect(): stopping TelemetryLogger");
384 telemetry_logger.stop();
385 telemetry_logger = null;
387 if (altos_link != null) {
388 AltosDebug.debug("disconnect(): stopping AltosDroidLink");
393 telemetry_state.config = null;
395 AltosDebug.debug("disconnect(): send message to clients");
397 if (clients.isEmpty()) {
398 AltosDebug.debug("disconnect(): no clients, terminating");
404 private void start_usb(UsbDevice device) {
405 AltosUsb d = new AltosUsb(this, device, handler);
412 } catch (InterruptedException ie) {
417 private void delete_serial(int serial) {
418 telemetry_state.states.remove((Integer) serial);
419 AltosPreferences.remove_state(serial);
423 private void start_altos_bluetooth(DeviceAddress address, boolean pause) {
424 if (bluetooth_adapter == null || !bluetooth_adapter.isEnabled())
429 // Get the BluetoothDevice object
430 BluetoothDevice device = bluetooth_adapter.getRemoteDevice(address.address);
432 this.address = address;
433 AltosDebug.debug("start_altos_bluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress());
434 altos_link = new AltosBluetooth(device, handler, pause);
435 telemetry_state.connect = TelemetryState.CONNECT_CONNECTING;
436 telemetry_state.address = address;
440 private void start_idle_monitor() {
441 if (altos_link != null && idle_monitor == null) {
443 idle_monitor = new AltosIdleMonitor(this, altos_link, true, false);
444 idle_monitor.set_callsign(AltosPreferences.callsign());
445 idle_monitor.start();
446 send_idle_mode_to_clients();
450 private void stop_idle_monitor() {
451 if (idle_monitor != null) {
453 idle_monitor.abort();
454 } catch (InterruptedException ie) {
458 send_idle_mode_to_clients();
462 private void reboot_remote() {
463 if (altos_link != null) {
466 altos_link.start_remote();
467 altos_link.printf("r eboot\n");
468 altos_link.flush_output();
469 } catch (TimeoutException te) {
470 } catch (InterruptedException ie) {
473 altos_link.stop_remote();
474 } catch (InterruptedException ie) {
480 private void ensure_ignite() {
482 ignite = new AltosIgnite(altos_link, true, false);
485 private synchronized void igniter_query(Messenger client) {
487 HashMap<String,Integer> status_map = null;
488 ignite_running = true;
492 status_map = ignite.status();
493 } catch (InterruptedException ie) {
494 AltosDebug.debug("ignite.status interrupted");
495 } catch (TimeoutException te) {
496 AltosDebug.debug("ignite.status timeout");
499 ignite_running = false;
501 Message m = Message.obtain(null, AltosDroid.MSG_IGNITER_STATUS, status_map);
504 } catch (RemoteException e) {
508 private synchronized void igniter_fire(String igniter) {
510 ignite_running = true;
513 ignite.fire(igniter);
514 } catch (InterruptedException ie) {
516 ignite_running = false;
520 // Timer for receiver battery voltage monitoring
521 Timer receiver_voltage_timer;
523 private void update_receiver_voltage() {
524 if (altos_link != null && idle_monitor == null && !ignite_running) {
526 double voltage = altos_link.monitor_battery();
527 telemetry_state.receiver_battery = voltage;
529 } catch (InterruptedException ie) {
534 private void stop_receiver_voltage_timer() {
535 if (receiver_voltage_timer != null) {
536 receiver_voltage_timer.cancel();
537 receiver_voltage_timer.purge();
538 receiver_voltage_timer = null;
542 private void start_receiver_voltage_timer() {
543 if (receiver_voltage_timer == null && altos_link.has_monitor_battery()) {
544 receiver_voltage_timer = new Timer();
545 receiver_voltage_timer.scheduleAtFixedRate(new TimerTask() { public void run() {update_receiver_voltage();}}, 1000L, 10000L);
549 private void connected() throws InterruptedException {
550 AltosDebug.debug("connected top");
551 AltosDebug.check_ui("connected\n");
553 if (altos_link == null)
554 throw new InterruptedException("no bluetooth");
555 telemetry_state.config = altos_link.config_data();
556 altos_link.set_radio_frequency(telemetry_state.frequency);
557 altos_link.set_telemetry_rate(telemetry_state.telemetry_rate);
558 } catch (TimeoutException e) {
559 // If this timed out, then we really want to retry it, but
560 // probably safer to just retry the connection from scratch.
561 AltosDebug.debug("connected timeout");
562 if (address != null) {
563 AltosDebug.debug("connected timeout, retrying");
564 start_altos_bluetooth(address, true);
566 handler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
572 AltosDebug.debug("connected bluetooth configured");
573 telemetry_state.connect = TelemetryState.CONNECT_CONNECTED;
574 telemetry_state.address = address;
578 AltosDebug.debug("connected TelemetryReader started");
580 telemetry_logger = new TelemetryLogger(this, altos_link);
582 start_receiver_voltage_timer();
584 AltosDebug.debug("Notify UI of connection");
591 public void onCreate() {
593 AltosDebug.init(this);
595 // Initialise preferences
596 AltosDroidPreferences.init(this);
598 // Get local Bluetooth adapter
599 bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
601 telemetry_state = new TelemetryState();
603 // Create a reference to the NotificationManager so that we can update our notifcation text later
604 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
606 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
607 telemetry_state.address = null;
609 /* Pull the saved state information out of the preferences database
611 ArrayList<Integer> serials = AltosPreferences.list_states();
613 telemetry_state.latest_serial = AltosPreferences.latest_state();
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",
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);
636 public int onStartCommand(Intent intent, int flags, int startId) {
637 AltosDebug.debug("Received start id %d: %s", startId, intent);
639 CharSequence text = getText(R.string.telemetry_service_started);
641 // Create notification to be displayed while the service runs
642 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
644 // The PendingIntent to launch our activity if the user selects this notification
645 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
646 new Intent(this, AltosDroid.class), 0);
648 // Set the info for the views that show in the notification panel.
649 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
651 // Set the notification to be in the "Ongoing" section.
652 notification.flags |= Notification.FLAG_ONGOING_EVENT;
654 // Move us into the foreground.
655 startForeground(NOTIFICATION, notification);
657 /* Start bluetooth if we don't have a connection already */
658 if (intent != null &&
659 (telemetry_state.connect == TelemetryState.CONNECT_NONE ||
660 telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED))
662 String action = intent.getAction();
664 if (action.equals(AltosDroid.ACTION_BLUETOOTH)) {
665 DeviceAddress address = AltosDroidPreferences.active_device();
666 if (address != null && !address.address.startsWith("USB"))
667 start_altos_bluetooth(address, false);
671 // We want this service to continue running until it is explicitly
672 // stopped, so return sticky.
677 public void onDestroy() {
679 // Stop the bluetooth Comms threads
682 // Demote us from the foreground, and cancel the persistent notification.
683 stopForeground(true);
685 // Tell the user we stopped.
686 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
690 public IBinder onBind(Intent intent) {
691 return messenger.getBinder();
694 /* AltosIdleMonitorListener */
695 public void update(AltosState state, AltosListenerState listener_state) {
696 telemetry_state.states.put(state.serial, state);
697 telemetry_state.receiver_battery = listener_state.battery;
701 public void failed() {
704 public void error(String reason) {