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_11.*;
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");
132 AltosDroidPreferences.set_active_device(null);
135 case MSG_DELETE_SERIAL:
136 AltosDebug.debug("Delete Serial command received");
137 s.delete_serial((Integer) msg.obj);
139 case MSG_SETFREQUENCY:
140 AltosDebug.debug("MSG_SETFREQUENCY");
141 s.telemetry_state.frequency = (Double) msg.obj;
142 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
144 s.altos_link.set_radio_frequency(s.telemetry_state.frequency);
145 s.altos_link.save_frequency();
146 } catch (InterruptedException e) {
147 } catch (TimeoutException e) {
153 AltosDebug.debug("MSG_SETBAUD");
154 s.telemetry_state.telemetry_rate = (Integer) msg.obj;
155 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
156 s.altos_link.set_telemetry_rate(s.telemetry_state.telemetry_rate);
157 s.altos_link.save_telemetry_rate();
163 *Messages from AltosBluetooth
166 AltosDebug.debug("MSG_CONNECTED");
167 bt = (AltosDroidLink) msg.obj;
169 if (bt != s.altos_link) {
170 AltosDebug.debug("Stale message");
173 AltosDebug.debug("Connected to device");
176 } catch (InterruptedException ie) {
179 case MSG_CONNECT_FAILED:
180 AltosDebug.debug("MSG_CONNECT_FAILED");
181 bt = (AltosDroidLink) msg.obj;
183 if (bt != s.altos_link) {
184 AltosDebug.debug("Stale message");
187 if (s.address != null) {
188 AltosDebug.debug("Connection failed... retrying");
189 s.start_altos_bluetooth(s.address, true);
194 case MSG_DISCONNECTED:
196 /* This can be sent by either AltosDroidLink or TelemetryReader */
197 AltosDebug.debug("MSG_DISCONNECTED");
198 bt = (AltosDroidLink) msg.obj;
200 if (bt != s.altos_link) {
201 AltosDebug.debug("Stale message");
204 if (s.address != null) {
205 AltosDebug.debug("Connection lost... retrying");
206 s.start_altos_bluetooth(s.address, true);
213 * Messages from TelemetryReader
216 s.telemetry((AltosTelemetry) msg.obj);
219 // forward crc error messages
220 s.telemetry_state.crc_errors = (Integer) msg.obj;
223 case MSG_BLUETOOTH_ENABLED:
224 AltosDebug.debug("TelemetryService notes that BT is now enabled");
225 address = AltosDroidPreferences.active_device();
226 if (address != null && !address.address.startsWith("USB"))
227 s.start_altos_bluetooth(address, false);
229 case MSG_MONITOR_IDLE_START:
230 AltosDebug.debug("start monitor idle");
231 s.start_idle_monitor();
233 case MSG_MONITOR_IDLE_STOP:
234 AltosDebug.debug("stop monitor idle");
235 s.stop_idle_monitor();
238 AltosDebug.debug("reboot");
241 case MSG_IGNITER_QUERY:
242 AltosDebug.debug("igniter query");
243 s.igniter_query(msg.replyTo);
245 case MSG_IGNITER_FIRE:
246 AltosDebug.debug("igniter fire");
247 s.igniter_fire((String) msg.obj);
250 super.handleMessage(msg);
255 /* Handle telemetry packet
257 private void telemetry(AltosTelemetry telem) {
260 if (telemetry_state.states.containsKey(telem.serial))
261 state = telemetry_state.states.get(telem.serial).clone();
263 state = new AltosState();
264 telem.update_state(state);
265 telemetry_state.states.put(telem.serial, state);
267 AltosPreferences.set_state(state);
272 /* Construct the message to deliver to clients
274 private Message message() {
275 if (telemetry_state == null)
276 AltosDebug.debug("telemetry_state null!");
277 if (telemetry_state.states == null)
278 AltosDebug.debug("telemetry_state.states null!");
279 return Message.obtain(null, AltosDroid.MSG_STATE, telemetry_state);
282 /* A new friend has connected
284 private void add_client(Messenger client) {
287 AltosDebug.debug("Client bound to service");
289 /* On connect, send the current state to the new client
291 send_to_client(client);
292 send_idle_mode_to_client(client);
294 /* If we've got an address from a previous session, then
295 * go ahead and try to reconnect to the device
297 if (address != null && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
298 AltosDebug.debug("Reconnecting now...");
299 start_altos_bluetooth(address, false);
303 /* A client has disconnected, clean up
305 private void remove_client(Messenger client) {
306 clients.remove(client);
307 AltosDebug.debug("Client unbound from service");
309 /* When the list of clients is empty, stop the service if
310 * we have no current telemetry source
313 if (clients.isEmpty() && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
314 AltosDebug.debug("No clients, no connection. Stopping\n");
319 private void send_to_client(Messenger client) {
320 Message m = message();
323 } catch (RemoteException e) {
324 AltosDebug.error("Client %s disappeared", client.toString());
325 remove_client(client);
329 private void send_to_clients() {
330 for (Messenger client : clients)
331 send_to_client(client);
334 private void send_idle_mode_to_client(Messenger client) {
335 Message m = Message.obtain(null, AltosDroid.MSG_IDLE_MODE, idle_monitor != null);
338 } catch (RemoteException e) {
339 AltosDebug.error("Client %s disappeared", client.toString());
340 remove_client(client);
344 private void send_idle_mode_to_clients() {
345 for (Messenger client : clients)
346 send_idle_mode_to_client(client);
349 private void telemetry_start() {
350 if (telemetry_reader == null && idle_monitor == null && !ignite_running) {
351 telemetry_reader = new TelemetryReader(altos_link, handler);
352 telemetry_reader.start();
356 private void telemetry_stop() {
357 if (telemetry_reader != null) {
358 AltosDebug.debug("disconnect(): stopping TelemetryReader");
359 telemetry_reader.interrupt();
361 telemetry_reader.join();
362 } catch (InterruptedException e) {
364 telemetry_reader = null;
368 private void disconnect(boolean notify) {
369 AltosDebug.debug("disconnect(): begin");
371 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
372 telemetry_state.address = null;
374 if (idle_monitor != null)
377 if (altos_link != null)
378 altos_link.closing();
380 stop_receiver_voltage_timer();
383 if (telemetry_logger != null) {
384 AltosDebug.debug("disconnect(): stopping TelemetryLogger");
385 telemetry_logger.stop();
386 telemetry_logger = null;
388 if (altos_link != null) {
389 AltosDebug.debug("disconnect(): stopping AltosDroidLink");
394 telemetry_state.config = null;
396 AltosDebug.debug("disconnect(): send message to clients");
398 if (clients.isEmpty()) {
399 AltosDebug.debug("disconnect(): no clients, terminating");
405 private void start_usb(UsbDevice device) {
406 AltosUsb d = new AltosUsb(this, device, handler);
413 } catch (InterruptedException ie) {
418 private void delete_serial(int serial) {
419 telemetry_state.states.remove((Integer) serial);
420 AltosPreferences.remove_state(serial);
424 private void start_altos_bluetooth(DeviceAddress address, boolean pause) {
425 if (bluetooth_adapter == null || !bluetooth_adapter.isEnabled())
430 // Get the BluetoothDevice object
431 BluetoothDevice device = bluetooth_adapter.getRemoteDevice(address.address);
433 this.address = address;
434 AltosDebug.debug("start_altos_bluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress());
435 altos_link = new AltosBluetooth(device, handler, pause);
436 telemetry_state.connect = TelemetryState.CONNECT_CONNECTING;
437 telemetry_state.address = address;
441 private void start_idle_monitor() {
442 if (altos_link != null && idle_monitor == null) {
444 idle_monitor = new AltosIdleMonitor(this, altos_link, true, false);
445 idle_monitor.set_callsign(AltosPreferences.callsign());
446 idle_monitor.start();
447 send_idle_mode_to_clients();
451 private void stop_idle_monitor() {
452 if (idle_monitor != null) {
454 idle_monitor.abort();
455 } catch (InterruptedException ie) {
459 send_idle_mode_to_clients();
463 private void reboot_remote() {
464 if (altos_link != null) {
467 altos_link.start_remote();
468 altos_link.printf("r eboot\n");
469 altos_link.flush_output();
470 } catch (TimeoutException te) {
471 } catch (InterruptedException ie) {
474 altos_link.stop_remote();
475 } catch (InterruptedException ie) {
481 private void ensure_ignite() {
483 ignite = new AltosIgnite(altos_link, true, false);
486 private synchronized void igniter_query(Messenger client) {
488 HashMap<String,Integer> status_map = null;
489 ignite_running = true;
493 status_map = ignite.status();
494 } catch (InterruptedException ie) {
495 AltosDebug.debug("ignite.status interrupted");
496 } catch (TimeoutException te) {
497 AltosDebug.debug("ignite.status timeout");
500 ignite_running = false;
502 Message m = Message.obtain(null, AltosDroid.MSG_IGNITER_STATUS, status_map);
505 } catch (RemoteException e) {
509 private synchronized void igniter_fire(String igniter) {
511 ignite_running = true;
514 ignite.fire(igniter);
515 } catch (InterruptedException ie) {
517 ignite_running = false;
521 // Timer for receiver battery voltage monitoring
522 Timer receiver_voltage_timer;
524 private void update_receiver_voltage() {
525 if (altos_link != null && idle_monitor == null && !ignite_running) {
527 double voltage = altos_link.monitor_battery();
528 telemetry_state.receiver_battery = voltage;
530 } catch (InterruptedException ie) {
535 private void stop_receiver_voltage_timer() {
536 if (receiver_voltage_timer != null) {
537 receiver_voltage_timer.cancel();
538 receiver_voltage_timer.purge();
539 receiver_voltage_timer = null;
543 private void start_receiver_voltage_timer() {
544 if (receiver_voltage_timer == null && altos_link.has_monitor_battery()) {
545 receiver_voltage_timer = new Timer();
546 receiver_voltage_timer.scheduleAtFixedRate(new TimerTask() { public void run() {update_receiver_voltage();}}, 1000L, 10000L);
550 private void connected() throws InterruptedException {
551 AltosDebug.debug("connected top");
552 AltosDebug.check_ui("connected\n");
554 if (altos_link == null)
555 throw new InterruptedException("no bluetooth");
556 telemetry_state.config = altos_link.config_data();
557 altos_link.set_radio_frequency(telemetry_state.frequency);
558 altos_link.set_telemetry_rate(telemetry_state.telemetry_rate);
559 } catch (TimeoutException e) {
560 // If this timed out, then we really want to retry it, but
561 // probably safer to just retry the connection from scratch.
562 AltosDebug.debug("connected timeout");
563 if (address != null) {
564 AltosDebug.debug("connected timeout, retrying");
565 start_altos_bluetooth(address, true);
567 handler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
573 AltosDebug.debug("connected bluetooth configured");
574 telemetry_state.connect = TelemetryState.CONNECT_CONNECTED;
575 telemetry_state.address = address;
579 AltosDebug.debug("connected TelemetryReader started");
581 telemetry_logger = new TelemetryLogger(this, altos_link);
583 start_receiver_voltage_timer();
585 AltosDebug.debug("Notify UI of connection");
592 public void onCreate() {
594 AltosDebug.init(this);
596 // Initialise preferences
597 AltosDroidPreferences.init(this);
599 // Get local Bluetooth adapter
600 bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
602 telemetry_state = new TelemetryState();
604 // Create a reference to the NotificationManager so that we can update our notifcation text later
605 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
607 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
608 telemetry_state.address = null;
610 /* Pull the saved state information out of the preferences database
612 ArrayList<Integer> serials = AltosPreferences.list_states();
614 telemetry_state.latest_serial = AltosPreferences.latest_state();
616 for (int serial : serials) {
617 AltosState saved_state = AltosPreferences.state(serial);
618 if (saved_state != null) {
619 if (telemetry_state.latest_serial == 0)
620 telemetry_state.latest_serial = serial;
622 AltosDebug.debug("recovered old state serial %d flight %d",
625 if (saved_state.gps != null)
626 AltosDebug.debug("\tposition %f,%f",
628 saved_state.gps.lon);
629 telemetry_state.states.put(serial, saved_state);
631 AltosDebug.debug("Failed to recover state for %d", serial);
637 public int onStartCommand(Intent intent, int flags, int startId) {
638 AltosDebug.debug("Received start id %d: %s", startId, intent);
640 CharSequence text = getText(R.string.telemetry_service_started);
642 // Create notification to be displayed while the service runs
643 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
645 // The PendingIntent to launch our activity if the user selects this notification
646 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
647 new Intent(this, AltosDroid.class), 0);
649 // Set the info for the views that show in the notification panel.
650 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
652 // Set the notification to be in the "Ongoing" section.
653 notification.flags |= Notification.FLAG_ONGOING_EVENT;
655 // Move us into the foreground.
656 startForeground(NOTIFICATION, notification);
658 /* Start bluetooth if we don't have a connection already */
659 if (intent != null &&
660 (telemetry_state.connect == TelemetryState.CONNECT_NONE ||
661 telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED))
663 String action = intent.getAction();
665 if (action.equals(AltosDroid.ACTION_BLUETOOTH)) {
666 DeviceAddress address = AltosDroidPreferences.active_device();
667 if (address != null && !address.address.startsWith("USB"))
668 start_altos_bluetooth(address, false);
672 // We want this service to continue running until it is explicitly
673 // stopped, so return sticky.
678 public void onDestroy() {
680 // Stop the bluetooth Comms threads
683 // Demote us from the foreground, and cancel the persistent notification.
684 stopForeground(true);
686 // Tell the user we stopped.
687 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
691 public IBinder onBind(Intent intent) {
692 return messenger.getBinder();
695 /* AltosIdleMonitorListener */
696 public void update(AltosState state, AltosListenerState listener_state) {
697 telemetry_state.states.put(state.serial, state);
698 telemetry_state.receiver_battery = listener_state.battery;
702 public void failed() {
705 public void error(String reason) {