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 if (!(Boolean) msg.obj)
133 AltosDroidPreferences.set_active_device(null);
136 case MSG_DELETE_SERIAL:
137 AltosDebug.debug("Delete Serial command received");
138 s.delete_serial((Integer) msg.obj);
140 case MSG_SETFREQUENCY:
141 AltosDebug.debug("MSG_SETFREQUENCY");
142 s.telemetry_state.frequency = (Double) msg.obj;
143 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
145 s.altos_link.set_radio_frequency(s.telemetry_state.frequency);
146 s.altos_link.save_frequency();
147 } catch (InterruptedException e) {
148 } catch (TimeoutException e) {
154 AltosDebug.debug("MSG_SETBAUD");
155 s.telemetry_state.telemetry_rate = (Integer) msg.obj;
156 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
157 s.altos_link.set_telemetry_rate(s.telemetry_state.telemetry_rate);
158 s.altos_link.save_telemetry_rate();
164 *Messages from AltosBluetooth
167 AltosDebug.debug("MSG_CONNECTED");
168 bt = (AltosDroidLink) msg.obj;
170 if (bt != s.altos_link) {
171 AltosDebug.debug("Stale message");
174 AltosDebug.debug("Connected to device");
177 } catch (InterruptedException ie) {
180 case MSG_CONNECT_FAILED:
181 AltosDebug.debug("MSG_CONNECT_FAILED");
182 bt = (AltosDroidLink) msg.obj;
184 if (bt != s.altos_link) {
185 AltosDebug.debug("Stale message");
188 if (s.address != null) {
189 AltosDebug.debug("Connection failed... retrying");
190 s.start_altos_bluetooth(s.address, true);
195 case MSG_DISCONNECTED:
197 /* This can be sent by either AltosDroidLink or TelemetryReader */
198 AltosDebug.debug("MSG_DISCONNECTED");
199 bt = (AltosDroidLink) msg.obj;
201 if (bt != s.altos_link) {
202 AltosDebug.debug("Stale message");
205 if (s.address != null) {
206 AltosDebug.debug("Connection lost... retrying");
207 s.start_altos_bluetooth(s.address, true);
214 * Messages from TelemetryReader
217 s.telemetry((AltosTelemetry) msg.obj);
220 // forward crc error messages
221 s.telemetry_state.crc_errors = (Integer) msg.obj;
224 case MSG_BLUETOOTH_ENABLED:
225 AltosDebug.debug("TelemetryService notes that BT is now enabled");
226 address = AltosDroidPreferences.active_device();
227 if (address != null && !address.address.startsWith("USB"))
228 s.start_altos_bluetooth(address, false);
230 case MSG_MONITOR_IDLE_START:
231 AltosDebug.debug("start monitor idle");
232 s.start_idle_monitor();
234 case MSG_MONITOR_IDLE_STOP:
235 AltosDebug.debug("stop monitor idle");
236 s.stop_idle_monitor();
239 AltosDebug.debug("reboot");
242 case MSG_IGNITER_QUERY:
243 AltosDebug.debug("igniter query");
244 s.igniter_query(msg.replyTo);
246 case MSG_IGNITER_FIRE:
247 AltosDebug.debug("igniter fire");
248 s.igniter_fire((String) msg.obj);
251 super.handleMessage(msg);
256 /* Handle telemetry packet
258 private void telemetry(AltosTelemetry telem) {
261 if (telemetry_state.states.containsKey(telem.serial))
262 state = telemetry_state.states.get(telem.serial).clone();
264 state = new AltosState();
265 telem.update_state(state);
266 telemetry_state.states.put(telem.serial, state);
268 AltosPreferences.set_state(state);
273 /* Construct the message to deliver to clients
275 private Message message() {
276 if (telemetry_state == null)
277 AltosDebug.debug("telemetry_state null!");
278 if (telemetry_state.states == null)
279 AltosDebug.debug("telemetry_state.states null!");
280 return Message.obtain(null, AltosDroid.MSG_STATE, telemetry_state);
283 /* A new friend has connected
285 private void add_client(Messenger client) {
288 AltosDebug.debug("Client bound to service");
290 /* On connect, send the current state to the new client
292 send_to_client(client);
293 send_idle_mode_to_client(client);
295 /* If we've got an address from a previous session, then
296 * go ahead and try to reconnect to the device
298 if (address != null && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
299 AltosDebug.debug("Reconnecting now...");
300 start_altos_bluetooth(address, false);
304 /* A client has disconnected, clean up
306 private void remove_client(Messenger client) {
307 clients.remove(client);
308 AltosDebug.debug("Client unbound from service");
310 /* When the list of clients is empty, stop the service if
311 * we have no current telemetry source
314 if (clients.isEmpty() && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
315 AltosDebug.debug("No clients, no connection. Stopping\n");
320 private void send_to_client(Messenger client) {
321 Message m = message();
324 } catch (RemoteException e) {
325 AltosDebug.error("Client %s disappeared", client.toString());
326 remove_client(client);
330 private void send_to_clients() {
331 for (Messenger client : clients)
332 send_to_client(client);
335 private void send_idle_mode_to_client(Messenger client) {
336 Message m = Message.obtain(null, AltosDroid.MSG_IDLE_MODE, idle_monitor != null);
339 } catch (RemoteException e) {
340 AltosDebug.error("Client %s disappeared", client.toString());
341 remove_client(client);
345 private void send_idle_mode_to_clients() {
346 for (Messenger client : clients)
347 send_idle_mode_to_client(client);
350 private void telemetry_start() {
351 if (telemetry_reader == null && idle_monitor == null && !ignite_running) {
352 telemetry_reader = new TelemetryReader(altos_link, handler);
353 telemetry_reader.start();
357 private void telemetry_stop() {
358 if (telemetry_reader != null) {
359 AltosDebug.debug("disconnect(): stopping TelemetryReader");
360 telemetry_reader.interrupt();
362 telemetry_reader.join();
363 } catch (InterruptedException e) {
365 telemetry_reader = null;
369 private void disconnect(boolean notify) {
370 AltosDebug.debug("disconnect(): begin");
372 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
373 telemetry_state.address = null;
375 if (idle_monitor != null)
378 if (altos_link != null)
379 altos_link.closing();
381 stop_receiver_voltage_timer();
384 if (telemetry_logger != null) {
385 AltosDebug.debug("disconnect(): stopping TelemetryLogger");
386 telemetry_logger.stop();
387 telemetry_logger = null;
389 if (altos_link != null) {
390 AltosDebug.debug("disconnect(): stopping AltosDroidLink");
395 telemetry_state.config = null;
397 AltosDebug.debug("disconnect(): send message to clients");
399 if (clients.isEmpty()) {
400 AltosDebug.debug("disconnect(): no clients, terminating");
406 private void start_usb(UsbDevice device) {
407 AltosUsb d = new AltosUsb(this, device, handler);
414 } catch (InterruptedException ie) {
419 private void delete_serial(int serial) {
420 telemetry_state.states.remove((Integer) serial);
421 AltosPreferences.remove_state(serial);
425 private void start_altos_bluetooth(DeviceAddress address, boolean pause) {
426 if (bluetooth_adapter == null || !bluetooth_adapter.isEnabled())
431 // Get the BluetoothDevice object
432 BluetoothDevice device = bluetooth_adapter.getRemoteDevice(address.address);
434 this.address = address;
435 AltosDebug.debug("start_altos_bluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress());
436 altos_link = new AltosBluetooth(device, handler, pause);
437 telemetry_state.connect = TelemetryState.CONNECT_CONNECTING;
438 telemetry_state.address = address;
442 private void start_idle_monitor() {
443 if (altos_link != null && idle_monitor == null) {
445 idle_monitor = new AltosIdleMonitor(this, altos_link, true, false);
446 idle_monitor.set_callsign(AltosPreferences.callsign());
447 idle_monitor.start();
448 send_idle_mode_to_clients();
452 private void stop_idle_monitor() {
453 if (idle_monitor != null) {
455 idle_monitor.abort();
456 } catch (InterruptedException ie) {
460 send_idle_mode_to_clients();
464 private void reboot_remote() {
465 if (altos_link != null) {
468 altos_link.start_remote();
469 altos_link.printf("r eboot\n");
470 altos_link.flush_output();
471 } catch (TimeoutException te) {
472 } catch (InterruptedException ie) {
475 altos_link.stop_remote();
476 } catch (InterruptedException ie) {
482 private void ensure_ignite() {
484 ignite = new AltosIgnite(altos_link, true, false);
487 private synchronized void igniter_query(Messenger client) {
489 HashMap<String,Integer> status_map = null;
490 ignite_running = true;
494 status_map = ignite.status();
495 } catch (InterruptedException ie) {
496 AltosDebug.debug("ignite.status interrupted");
497 } catch (TimeoutException te) {
498 AltosDebug.debug("ignite.status timeout");
501 ignite_running = false;
503 Message m = Message.obtain(null, AltosDroid.MSG_IGNITER_STATUS, status_map);
506 } catch (RemoteException e) {
510 private synchronized void igniter_fire(String igniter) {
512 ignite_running = true;
515 ignite.fire(igniter);
516 } catch (InterruptedException ie) {
518 ignite_running = false;
522 // Timer for receiver battery voltage monitoring
523 Timer receiver_voltage_timer;
525 private void update_receiver_voltage() {
526 if (altos_link != null && idle_monitor == null && !ignite_running) {
528 double voltage = altos_link.monitor_battery();
529 telemetry_state.receiver_battery = voltage;
531 } catch (InterruptedException ie) {
536 private void stop_receiver_voltage_timer() {
537 if (receiver_voltage_timer != null) {
538 receiver_voltage_timer.cancel();
539 receiver_voltage_timer.purge();
540 receiver_voltage_timer = null;
544 private void start_receiver_voltage_timer() {
545 if (receiver_voltage_timer == null && altos_link.has_monitor_battery()) {
546 receiver_voltage_timer = new Timer();
547 receiver_voltage_timer.scheduleAtFixedRate(new TimerTask() { public void run() {update_receiver_voltage();}}, 1000L, 10000L);
551 private void connected() throws InterruptedException {
552 AltosDebug.debug("connected top");
553 AltosDebug.check_ui("connected\n");
555 if (altos_link == null)
556 throw new InterruptedException("no bluetooth");
557 telemetry_state.config = altos_link.config_data();
558 altos_link.set_radio_frequency(telemetry_state.frequency);
559 altos_link.set_telemetry_rate(telemetry_state.telemetry_rate);
560 } catch (TimeoutException e) {
561 // If this timed out, then we really want to retry it, but
562 // probably safer to just retry the connection from scratch.
563 AltosDebug.debug("connected timeout");
564 if (address != null) {
565 AltosDebug.debug("connected timeout, retrying");
566 start_altos_bluetooth(address, true);
568 handler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
574 AltosDebug.debug("connected bluetooth configured");
575 telemetry_state.connect = TelemetryState.CONNECT_CONNECTED;
576 telemetry_state.address = address;
580 AltosDebug.debug("connected TelemetryReader started");
582 telemetry_logger = new TelemetryLogger(this, altos_link);
584 start_receiver_voltage_timer();
586 AltosDebug.debug("Notify UI of connection");
593 public void onCreate() {
595 AltosDebug.init(this);
597 // Initialise preferences
598 AltosDroidPreferences.init(this);
600 // Get local Bluetooth adapter
601 bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
603 telemetry_state = new TelemetryState();
605 // Create a reference to the NotificationManager so that we can update our notifcation text later
606 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
608 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
609 telemetry_state.address = null;
611 /* Pull the saved state information out of the preferences database
613 ArrayList<Integer> serials = AltosPreferences.list_states();
615 telemetry_state.latest_serial = AltosPreferences.latest_state();
617 AltosDebug.debug("latest serial %d\n", telemetry_state.latest_serial);
619 for (int serial : serials) {
620 AltosState saved_state = AltosPreferences.state(serial);
621 if (saved_state != null) {
622 if (telemetry_state.latest_serial == 0)
623 telemetry_state.latest_serial = serial;
625 AltosDebug.debug("recovered old state serial %d flight %d",
628 if (saved_state.gps != null)
629 AltosDebug.debug("\tposition %f,%f",
631 saved_state.gps.lon);
632 telemetry_state.states.put(serial, saved_state);
634 AltosDebug.debug("Failed to recover state for %d", serial);
635 AltosPreferences.remove_state(serial);
641 public int onStartCommand(Intent intent, int flags, int startId) {
642 AltosDebug.debug("Received start id %d: %s", startId, intent);
644 CharSequence text = getText(R.string.telemetry_service_started);
646 // Create notification to be displayed while the service runs
647 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
649 // The PendingIntent to launch our activity if the user selects this notification
650 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
651 new Intent(this, AltosDroid.class), 0);
653 // Set the info for the views that show in the notification panel.
654 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
656 // Set the notification to be in the "Ongoing" section.
657 notification.flags |= Notification.FLAG_ONGOING_EVENT;
659 // Move us into the foreground.
660 startForeground(NOTIFICATION, notification);
662 /* Start bluetooth if we don't have a connection already */
663 if (intent != null &&
664 (telemetry_state.connect == TelemetryState.CONNECT_NONE ||
665 telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED))
667 String action = intent.getAction();
669 if (action.equals(AltosDroid.ACTION_BLUETOOTH)) {
670 DeviceAddress address = AltosDroidPreferences.active_device();
671 if (address != null && !address.address.startsWith("USB"))
672 start_altos_bluetooth(address, false);
676 // We want this service to continue running until it is explicitly
677 // stopped, so return sticky.
682 public void onDestroy() {
684 // Stop the bluetooth Comms threads
687 // Demote us from the foreground, and cancel the persistent notification.
688 stopForeground(true);
690 // Tell the user we stopped.
691 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
695 public IBinder onBind(Intent intent) {
696 return messenger.getBinder();
699 /* AltosIdleMonitorListener */
700 public void update(AltosState state, AltosListenerState listener_state) {
701 telemetry_state.states.put(state.serial, state);
702 telemetry_state.receiver_battery = listener_state.battery;
706 public void failed() {
709 public void error(String reason) {