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.Location;
42 import android.location.LocationManager;
43 import android.location.LocationListener;
44 import android.location.Criteria;
46 import org.altusmetrum.altoslib_7.*;
48 public class TelemetryService extends Service implements LocationListener {
50 static final int MSG_REGISTER_CLIENT = 1;
51 static final int MSG_UNREGISTER_CLIENT = 2;
52 static final int MSG_CONNECT = 3;
53 static final int MSG_OPEN_USB = 4;
54 static final int MSG_CONNECTED = 5;
55 static final int MSG_CONNECT_FAILED = 6;
56 static final int MSG_DISCONNECTED = 7;
57 static final int MSG_TELEMETRY = 8;
58 static final int MSG_SETFREQUENCY = 9;
59 static final int MSG_CRC_ERROR = 10;
60 static final int MSG_SETBAUD = 11;
61 static final int MSG_DISCONNECT = 12;
62 static final int MSG_DELETE_SERIAL = 13;
64 // Unique Identification Number for the Notification.
65 // We use it on Notification start, and to cancel it.
66 private int NOTIFICATION = R.string.telemetry_service_label;
67 //private NotificationManager mNM;
69 ArrayList<Messenger> clients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
70 final Handler handler = new IncomingHandler(this);
71 final Messenger messenger = new Messenger(handler); // Target we publish for clients to send messages to IncomingHandler.
73 // Name of the connected device
74 DeviceAddress address;
75 private AltosDroidLink altos_link = null;
76 private TelemetryReader telemetry_reader = null;
77 private TelemetryLogger telemetry_logger = null;
79 // Local Bluetooth adapter
80 private BluetoothAdapter bluetooth_adapter = null;
82 // Last data seen; send to UI when it starts
83 private TelemetryState telemetry_state;
85 // Handler of incoming messages from clients.
86 static class IncomingHandler extends Handler {
87 private final WeakReference<TelemetryService> service;
88 IncomingHandler(TelemetryService s) { service = new WeakReference<TelemetryService>(s); }
91 public void handleMessage(Message msg) {
92 TelemetryService s = service.get();
93 AltosDroidLink bt = null;
98 /* Messages from application */
99 case MSG_REGISTER_CLIENT:
100 s.add_client(msg.replyTo);
102 case MSG_UNREGISTER_CLIENT:
103 s.remove_client(msg.replyTo);
106 AltosDebug.debug("Connect command received");
107 DeviceAddress address = (DeviceAddress) msg.obj;
108 AltosDroidPreferences.set_active_device(address);
109 s.start_altos_bluetooth(address, false);
112 AltosDebug.debug("Open USB command received");
113 UsbDevice device = (UsbDevice) msg.obj;
117 AltosDebug.debug("Disconnect command received");
121 case MSG_DELETE_SERIAL:
122 AltosDebug.debug("Delete Serial command received");
123 s.delete_serial((Integer) msg.obj);
125 case MSG_SETFREQUENCY:
126 AltosDebug.debug("MSG_SETFREQUENCY");
127 s.telemetry_state.frequency = (Double) msg.obj;
128 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
130 s.altos_link.set_radio_frequency(s.telemetry_state.frequency);
131 s.altos_link.save_frequency();
132 } catch (InterruptedException e) {
133 } catch (TimeoutException e) {
139 AltosDebug.debug("MSG_SETBAUD");
140 s.telemetry_state.telemetry_rate = (Integer) msg.obj;
141 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
142 s.altos_link.set_telemetry_rate(s.telemetry_state.telemetry_rate);
143 s.altos_link.save_telemetry_rate();
149 *Messages from AltosBluetooth
152 AltosDebug.debug("MSG_CONNECTED");
153 bt = (AltosDroidLink) msg.obj;
155 if (bt != s.altos_link) {
156 AltosDebug.debug("Stale message");
159 AltosDebug.debug("Connected to device");
162 } catch (InterruptedException ie) {
165 case MSG_CONNECT_FAILED:
166 AltosDebug.debug("MSG_CONNECT_FAILED");
167 bt = (AltosDroidLink) msg.obj;
169 if (bt != s.altos_link) {
170 AltosDebug.debug("Stale message");
173 if (s.address != null) {
174 AltosDebug.debug("Connection failed... retrying");
175 s.start_altos_bluetooth(s.address, true);
180 case MSG_DISCONNECTED:
182 /* This can be sent by either AltosDroidLink or TelemetryReader */
183 AltosDebug.debug("MSG_DISCONNECTED");
184 bt = (AltosDroidLink) msg.obj;
186 if (bt != s.altos_link) {
187 AltosDebug.debug("Stale message");
190 if (s.address != null) {
191 AltosDebug.debug("Connection lost... retrying");
192 s.start_altos_bluetooth(s.address, true);
199 * Messages from TelemetryReader
202 s.telemetry((AltosTelemetry) msg.obj);
205 // forward crc error messages
206 s.telemetry_state.crc_errors = (Integer) msg.obj;
210 super.handleMessage(msg);
215 /* Handle telemetry packet
217 private void telemetry(AltosTelemetry telem) {
220 if (telemetry_state.states.containsKey(telem.serial))
221 state = telemetry_state.states.get(telem.serial).clone();
223 state = new AltosState();
224 telem.update_state(state);
225 telemetry_state.states.put(telem.serial, state);
227 AltosPreferences.set_state(telem.serial, state, null);
232 /* Construct the message to deliver to clients
234 private Message message() {
235 if (telemetry_state == null)
236 AltosDebug.debug("telemetry_state null!");
237 if (telemetry_state.states == null)
238 AltosDebug.debug("telemetry_state.states null!");
239 return Message.obtain(null, AltosDroid.MSG_STATE, telemetry_state);
242 /* A new friend has connected
244 private void add_client(Messenger client) {
247 AltosDebug.debug("Client bound to service");
249 /* On connect, send the current state to the new client
251 send_to_client(client, message());
253 /* If we've got an address from a previous session, then
254 * go ahead and try to reconnect to the device
256 if (address != null && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
257 AltosDebug.debug("Reconnecting now...");
258 start_altos_bluetooth(address, false);
262 /* A client has disconnected, clean up
264 private void remove_client(Messenger client) {
265 clients.remove(client);
266 AltosDebug.debug("Client unbound from service");
268 /* When the list of clients is empty, stop the service if
269 * we have no current telemetry source
272 if (clients.isEmpty() && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
273 AltosDebug.debug("No clients, no connection. Stopping\n");
278 private void send_to_client(Messenger client, Message m) {
281 } catch (RemoteException e) {
282 AltosDebug.error("Client %s disappeared", client.toString());
283 remove_client(client);
287 private void send_to_clients() {
288 Message m = message();
289 for (Messenger client : clients)
290 send_to_client(client, m);
293 private void disconnect(boolean notify) {
294 AltosDebug.debug("disconnect(): begin");
296 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
297 telemetry_state.address = null;
299 if (altos_link != null)
300 altos_link.closing();
302 stop_receiver_voltage_timer();
304 if (telemetry_reader != null) {
305 AltosDebug.debug("disconnect(): stopping TelemetryReader");
306 telemetry_reader.interrupt();
308 telemetry_reader.join();
309 } catch (InterruptedException e) {
311 telemetry_reader = null;
313 if (telemetry_logger != null) {
314 AltosDebug.debug("disconnect(): stopping TelemetryLogger");
315 telemetry_logger.stop();
316 telemetry_logger = null;
318 if (altos_link != null) {
319 AltosDebug.debug("disconnect(): stopping AltosDroidLink");
323 telemetry_state.config = null;
325 AltosDebug.debug("disconnect(): send message to clients");
327 if (clients.isEmpty()) {
328 AltosDebug.debug("disconnect(): no clients, terminating");
334 private void start_usb(UsbDevice device) {
335 AltosUsb d = new AltosUsb(this, device, handler);
342 } catch (InterruptedException ie) {
347 private void delete_serial(int serial) {
348 telemetry_state.states.remove((Integer) serial);
349 AltosPreferences.remove_state(serial);
353 private void start_altos_bluetooth(DeviceAddress address, boolean pause) {
354 // Get the BLuetoothDevice object
355 BluetoothDevice device = bluetooth_adapter.getRemoteDevice(address.address);
358 this.address = address;
359 AltosDebug.debug("start_altos_bluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress());
360 altos_link = new AltosBluetooth(device, handler, pause);
361 telemetry_state.connect = TelemetryState.CONNECT_CONNECTING;
362 telemetry_state.address = address;
366 // Timer for receiver battery voltage monitoring
367 Timer receiver_voltage_timer;
369 private void update_receiver_voltage() {
370 if (altos_link != null) {
372 double voltage = altos_link.monitor_battery();
373 telemetry_state.receiver_battery = voltage;
374 } catch (InterruptedException ie) {
379 private void stop_receiver_voltage_timer() {
380 if (receiver_voltage_timer != null) {
381 receiver_voltage_timer.cancel();
382 receiver_voltage_timer.purge();
383 receiver_voltage_timer = null;
387 private void start_receiver_voltage_timer() {
388 if (receiver_voltage_timer == null && altos_link.has_monitor_battery()) {
389 receiver_voltage_timer = new Timer();
390 receiver_voltage_timer.scheduleAtFixedRate(new TimerTask() { public void run() {update_receiver_voltage();}}, 1000L, 10000L);
394 private void connected() throws InterruptedException {
395 AltosDebug.debug("connected top");
396 AltosDebug.check_ui("connected\n");
398 if (altos_link == null)
399 throw new InterruptedException("no bluetooth");
400 telemetry_state.config = altos_link.config_data();
401 altos_link.set_radio_frequency(telemetry_state.frequency);
402 altos_link.set_telemetry_rate(telemetry_state.telemetry_rate);
403 } catch (TimeoutException e) {
404 // If this timed out, then we really want to retry it, but
405 // probably safer to just retry the connection from scratch.
406 AltosDebug.debug("connected timeout");
407 if (address != null) {
408 AltosDebug.debug("connected timeout, retrying");
409 start_altos_bluetooth(address, true);
411 handler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
417 AltosDebug.debug("connected bluetooth configured");
418 telemetry_state.connect = TelemetryState.CONNECT_CONNECTED;
419 telemetry_state.address = address;
421 telemetry_reader = new TelemetryReader(altos_link, handler);
422 telemetry_reader.start();
424 AltosDebug.debug("connected TelemetryReader started");
426 telemetry_logger = new TelemetryLogger(this, altos_link);
428 start_receiver_voltage_timer();
430 AltosDebug.debug("Notify UI of connection");
437 public void onCreate() {
439 AltosDebug.init(this);
441 // Initialise preferences
442 AltosDroidPreferences.init(this);
444 // Get local Bluetooth adapter
445 bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
447 // If the adapter is null, then Bluetooth is not supported
448 if (bluetooth_adapter == null) {
449 Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
452 telemetry_state = new TelemetryState();
454 // Create a reference to the NotificationManager so that we can update our notifcation text later
455 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
457 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
458 telemetry_state.address = null;
460 /* Pull the saved state information out of the preferences database
462 ArrayList<Integer> serials = AltosPreferences.list_states();
464 telemetry_state.latest_serial = AltosPreferences.latest_state();
466 for (int serial : serials) {
467 AltosSavedState saved_state = AltosPreferences.state(serial);
468 if (saved_state != null) {
470 serial = saved_state.state.serial;
471 AltosPreferences.set_state(serial, saved_state.state, saved_state.listener_state);
472 AltosPreferences.remove_state(0);
474 if (telemetry_state.latest_serial == 0)
475 telemetry_state.latest_serial = serial;
477 AltosDebug.debug("recovered old state serial %d flight %d\n",
479 saved_state.state.flight);
480 if (saved_state.state.gps != null)
481 AltosDebug.debug("\tposition %f,%f\n",
482 saved_state.state.gps.lat,
483 saved_state.state.gps.lon);
484 telemetry_state.states.put(serial, saved_state.state);
488 // Listen for GPS and Network position updates
489 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
491 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
495 public int onStartCommand(Intent intent, int flags, int startId) {
496 AltosDebug.debug("Received start id %d: %s", startId, intent);
498 CharSequence text = getText(R.string.telemetry_service_started);
500 // Create notification to be displayed while the service runs
501 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
503 // The PendingIntent to launch our activity if the user selects this notification
504 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
505 new Intent(this, AltosDroid.class), 0);
507 // Set the info for the views that show in the notification panel.
508 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
510 // Set the notification to be in the "Ongoing" section.
511 notification.flags |= Notification.FLAG_ONGOING_EVENT;
513 // Move us into the foreground.
514 startForeground(NOTIFICATION, notification);
516 /* Start bluetooth if we don't have a connection already */
517 if (intent != null &&
518 (telemetry_state.connect == TelemetryState.CONNECT_NONE ||
519 telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED))
521 String action = intent.getAction();
523 if (action.equals(AltosDroid.ACTION_BLUETOOTH)) {
524 DeviceAddress address = AltosDroidPreferences.active_device();
525 if (address != null && !address.address.startsWith("USB"))
526 start_altos_bluetooth(address, false);
530 // We want this service to continue running until it is explicitly
531 // stopped, so return sticky.
536 public void onDestroy() {
538 // Stop listening for location updates
539 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
541 // Stop the bluetooth Comms threads
544 // Demote us from the foreground, and cancel the persistent notification.
545 stopForeground(true);
547 // Tell the user we stopped.
548 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
552 public IBinder onBind(Intent intent) {
553 return messenger.getBinder();
557 public void onLocationChanged(Location location) {
558 telemetry_state.location = location;
559 AltosDebug.debug("location changed");
563 public void onStatusChanged(String provider, int status, Bundle extras) {
566 public void onProviderEnabled(String provider) {
569 public void onProviderDisabled(String provider) {