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_13.*;
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());
265 state = new AltosState(new AltosCalData());
266 telem.provide_data(state);
267 telemetry_state.states.put(telem.serial(), state);
268 telemetry_state.quiet = false;
270 AltosPreferences.set_state(state,telem.serial());
275 /* Construct the message to deliver to clients
277 private Message message() {
278 if (telemetry_state == null)
279 AltosDebug.debug("telemetry_state null!");
280 if (telemetry_state.states == null)
281 AltosDebug.debug("telemetry_state.states null!");
282 return Message.obtain(null, AltosDroid.MSG_STATE, telemetry_state);
285 /* A new friend has connected
287 private void add_client(Messenger client) {
290 AltosDebug.debug("Client bound to service");
292 /* On connect, send the current state to the new client
294 send_to_client(client);
295 send_idle_mode_to_client(client);
297 /* If we've got an address from a previous session, then
298 * go ahead and try to reconnect to the device
300 if (address != null && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
301 AltosDebug.debug("Reconnecting now...");
302 start_altos_bluetooth(address, false);
306 /* A client has disconnected, clean up
308 private void remove_client(Messenger client) {
309 clients.remove(client);
310 AltosDebug.debug("Client unbound from service");
312 /* When the list of clients is empty, stop the service if
313 * we have no current telemetry source
316 if (clients.isEmpty() && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
317 AltosDebug.debug("No clients, no connection. Stopping\n");
322 private void send_to_client(Messenger client) {
323 Message m = message();
326 } catch (RemoteException e) {
327 AltosDebug.error("Client %s disappeared", client.toString());
328 remove_client(client);
332 private void send_to_clients() {
333 for (Messenger client : clients)
334 send_to_client(client);
337 private void send_idle_mode_to_client(Messenger client) {
338 Message m = Message.obtain(null, AltosDroid.MSG_IDLE_MODE, idle_monitor != null);
341 } catch (RemoteException e) {
342 AltosDebug.error("Client %s disappeared", client.toString());
343 remove_client(client);
347 private void send_idle_mode_to_clients() {
348 for (Messenger client : clients)
349 send_idle_mode_to_client(client);
352 private void telemetry_start() {
353 if (telemetry_reader == null && idle_monitor == null && !ignite_running) {
354 telemetry_reader = new TelemetryReader(altos_link, handler);
355 telemetry_reader.start();
359 private void telemetry_stop() {
360 if (telemetry_reader != null) {
361 AltosDebug.debug("disconnect(): stopping TelemetryReader");
362 telemetry_reader.interrupt();
364 telemetry_reader.join();
365 } catch (InterruptedException e) {
367 telemetry_reader = null;
371 private void disconnect(boolean notify) {
372 AltosDebug.debug("disconnect(): begin");
374 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
375 telemetry_state.address = null;
377 if (idle_monitor != null)
380 if (altos_link != null)
381 altos_link.closing();
383 stop_receiver_voltage_timer();
386 if (telemetry_logger != null) {
387 AltosDebug.debug("disconnect(): stopping TelemetryLogger");
388 telemetry_logger.stop();
389 telemetry_logger = null;
391 if (altos_link != null) {
392 AltosDebug.debug("disconnect(): stopping AltosDroidLink");
397 telemetry_state.config = null;
399 AltosDebug.debug("disconnect(): send message to clients");
401 if (clients.isEmpty()) {
402 AltosDebug.debug("disconnect(): no clients, terminating");
408 private void start_usb(UsbDevice device) {
409 AltosUsb d = new AltosUsb(this, device, handler);
416 } catch (InterruptedException ie) {
421 private void delete_serial(int serial) {
422 telemetry_state.states.remove((Integer) serial);
423 AltosPreferences.remove_state(serial);
427 private void start_altos_bluetooth(DeviceAddress address, boolean pause) {
428 if (bluetooth_adapter == null || !bluetooth_adapter.isEnabled())
433 // Get the BluetoothDevice object
434 BluetoothDevice device = bluetooth_adapter.getRemoteDevice(address.address);
436 this.address = address;
437 AltosDebug.debug("start_altos_bluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress());
438 altos_link = new AltosBluetooth(device, handler, pause);
439 telemetry_state.connect = TelemetryState.CONNECT_CONNECTING;
440 telemetry_state.address = address;
444 private void start_idle_monitor() {
445 if (altos_link != null && idle_monitor == null) {
447 idle_monitor = new AltosIdleMonitor(this, altos_link, true, false);
448 idle_monitor.set_callsign(AltosPreferences.callsign());
449 idle_monitor.start();
450 send_idle_mode_to_clients();
454 private void stop_idle_monitor() {
455 if (idle_monitor != null) {
457 idle_monitor.abort();
458 } catch (InterruptedException ie) {
462 send_idle_mode_to_clients();
466 private void reboot_remote() {
467 if (altos_link != null) {
470 altos_link.start_remote();
471 altos_link.printf("r eboot\n");
472 altos_link.flush_output();
473 } catch (TimeoutException te) {
474 } catch (InterruptedException ie) {
477 altos_link.stop_remote();
478 } catch (InterruptedException ie) {
484 private void ensure_ignite() {
486 ignite = new AltosIgnite(altos_link, true, false);
489 private synchronized void igniter_query(Messenger client) {
491 HashMap<String,Integer> status_map = null;
492 ignite_running = true;
496 status_map = ignite.status();
497 } catch (InterruptedException ie) {
498 AltosDebug.debug("ignite.status interrupted");
499 } catch (TimeoutException te) {
500 AltosDebug.debug("ignite.status timeout");
503 ignite_running = false;
505 Message m = Message.obtain(null, AltosDroid.MSG_IGNITER_STATUS, status_map);
508 } catch (RemoteException e) {
512 private synchronized void igniter_fire(String igniter) {
514 ignite_running = true;
517 ignite.fire(igniter);
518 } catch (InterruptedException ie) {
520 ignite_running = false;
524 // Timer for receiver battery voltage monitoring
525 Timer receiver_voltage_timer;
527 private void update_receiver_voltage() {
528 if (altos_link != null && idle_monitor == null && !ignite_running) {
530 double voltage = altos_link.monitor_battery();
531 telemetry_state.receiver_battery = voltage;
533 } catch (InterruptedException ie) {
538 private void stop_receiver_voltage_timer() {
539 if (receiver_voltage_timer != null) {
540 receiver_voltage_timer.cancel();
541 receiver_voltage_timer.purge();
542 receiver_voltage_timer = null;
546 private void start_receiver_voltage_timer() {
547 if (receiver_voltage_timer == null && altos_link.has_monitor_battery()) {
548 receiver_voltage_timer = new Timer();
549 receiver_voltage_timer.scheduleAtFixedRate(new TimerTask() { public void run() {update_receiver_voltage();}}, 1000L, 10000L);
553 private void connected() throws InterruptedException {
554 AltosDebug.debug("connected top");
555 AltosDebug.check_ui("connected\n");
557 if (altos_link == null)
558 throw new InterruptedException("no bluetooth");
559 telemetry_state.config = altos_link.config_data();
560 altos_link.set_radio_frequency(telemetry_state.frequency);
561 altos_link.set_telemetry_rate(telemetry_state.telemetry_rate);
562 } catch (TimeoutException e) {
563 // If this timed out, then we really want to retry it, but
564 // probably safer to just retry the connection from scratch.
565 AltosDebug.debug("connected timeout");
566 if (address != null) {
567 AltosDebug.debug("connected timeout, retrying");
568 start_altos_bluetooth(address, true);
570 handler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
576 AltosDebug.debug("connected bluetooth configured");
577 telemetry_state.connect = TelemetryState.CONNECT_CONNECTED;
578 telemetry_state.address = address;
582 AltosDebug.debug("connected TelemetryReader started");
584 telemetry_logger = new TelemetryLogger(this, altos_link);
586 start_receiver_voltage_timer();
588 AltosDebug.debug("Notify UI of connection");
595 public void onCreate() {
597 AltosDebug.init(this);
599 // Initialise preferences
600 AltosDroidPreferences.init(this);
602 // Get local Bluetooth adapter
603 bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
605 telemetry_state = new TelemetryState();
607 // Create a reference to the NotificationManager so that we can update our notifcation text later
608 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
610 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
611 telemetry_state.address = null;
613 /* Pull the saved state information out of the preferences database
615 ArrayList<Integer> serials = AltosPreferences.list_states();
617 telemetry_state.latest_serial = AltosPreferences.latest_state();
619 telemetry_state.quiet = true;
621 AltosDebug.debug("latest serial %d\n", telemetry_state.latest_serial);
623 for (int serial : serials) {
624 AltosState saved_state = AltosPreferences.state(serial);
625 if (saved_state != null) {
626 if (telemetry_state.latest_serial == 0)
627 telemetry_state.latest_serial = serial;
629 AltosDebug.debug("recovered old state serial %d flight %d",
631 saved_state.cal_data().flight);
632 if (saved_state.gps != null)
633 AltosDebug.debug("\tposition %f,%f",
635 saved_state.gps.lon);
636 telemetry_state.states.put(serial, saved_state);
638 AltosDebug.debug("Failed to recover state for %d", serial);
639 AltosPreferences.remove_state(serial);
645 public int onStartCommand(Intent intent, int flags, int startId) {
646 AltosDebug.debug("Received start id %d: %s", startId, intent);
648 CharSequence text = getText(R.string.telemetry_service_started);
650 // Create notification to be displayed while the service runs
651 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
653 // The PendingIntent to launch our activity if the user selects this notification
654 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
655 new Intent(this, AltosDroid.class), 0);
657 // Set the info for the views that show in the notification panel.
658 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
660 // Set the notification to be in the "Ongoing" section.
661 notification.flags |= Notification.FLAG_ONGOING_EVENT;
663 // Move us into the foreground.
664 startForeground(NOTIFICATION, notification);
666 /* Start bluetooth if we don't have a connection already */
667 if (intent != null &&
668 (telemetry_state.connect == TelemetryState.CONNECT_NONE ||
669 telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED))
671 String action = intent.getAction();
673 if (action.equals(AltosDroid.ACTION_BLUETOOTH)) {
674 DeviceAddress address = AltosDroidPreferences.active_device();
675 if (address != null && !address.address.startsWith("USB"))
676 start_altos_bluetooth(address, false);
680 // We want this service to continue running until it is explicitly
681 // stopped, so return sticky.
686 public void onDestroy() {
688 // Stop the bluetooth Comms threads
691 // Demote us from the foreground, and cancel the persistent notification.
692 stopForeground(true);
694 // Tell the user we stopped.
695 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
699 public IBinder onBind(Intent intent) {
700 return messenger.getBinder();
703 /* AltosIdleMonitorListener */
704 public void update(AltosState state, AltosListenerState listener_state) {
705 telemetry_state.states.put(state.cal_data().serial, state);
706 telemetry_state.receiver_battery = listener_state.battery;
710 public void failed() {
713 public void error(String reason) {