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 AltosDebug.debug("MSG_TELEMETRY");
203 s.telemetry((AltosTelemetry) msg.obj);
206 // forward crc error messages
207 s.telemetry_state.crc_errors = (Integer) msg.obj;
208 AltosDebug.debug("MSG_CRC_ERROR");
212 super.handleMessage(msg);
217 /* Handle telemetry packet
219 private void telemetry(AltosTelemetry telem) {
222 if (telemetry_state.states.containsKey(telem.serial))
223 state = telemetry_state.states.get(telem.serial).clone();
225 state = new AltosState();
226 telem.update_state(state);
227 telemetry_state.states.put(telem.serial, state);
229 AltosDebug.debug("Save state %d", telem.serial);
230 AltosPreferences.set_state(telem.serial, state, null);
235 /* Construct the message to deliver to clients
237 private Message message() {
238 if (telemetry_state == null)
239 AltosDebug.debug("telemetry_state null!");
240 if (telemetry_state.states == null)
241 AltosDebug.debug("telemetry_state.states null!");
242 return Message.obtain(null, AltosDroid.MSG_STATE, telemetry_state);
245 /* A new friend has connected
247 private void add_client(Messenger client) {
250 AltosDebug.debug("Client bound to service");
252 /* On connect, send the current state to the new client
254 send_to_client(client, message());
256 /* If we've got an address from a previous session, then
257 * go ahead and try to reconnect to the device
259 if (address != null && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
260 AltosDebug.debug("Reconnecting now...");
261 start_altos_bluetooth(address, false);
265 /* A client has disconnected, clean up
267 private void remove_client(Messenger client) {
268 clients.remove(client);
269 AltosDebug.debug("Client unbound from service");
271 /* When the list of clients is empty, stop the service if
272 * we have no current telemetry source
275 if (clients.isEmpty() && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
276 AltosDebug.debug("No clients, no connection. Stopping\n");
281 private void send_to_client(Messenger client, Message m) {
283 AltosDebug.debug("Send message to client %s", client.toString());
285 } catch (RemoteException e) {
286 AltosDebug.error("Client %s disappeared", client.toString());
287 remove_client(client);
291 private void send_to_clients() {
292 Message m = message();
293 AltosDebug.debug("Send message to %d clients", clients.size());
294 for (Messenger client : clients)
295 send_to_client(client, m);
298 private void disconnect(boolean notify) {
299 AltosDebug.debug("disconnect(): begin");
301 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
302 telemetry_state.address = null;
304 if (altos_link != null)
305 altos_link.closing();
307 stop_receiver_voltage_timer();
309 if (telemetry_reader != null) {
310 AltosDebug.debug("disconnect(): stopping TelemetryReader");
311 telemetry_reader.interrupt();
313 telemetry_reader.join();
314 } catch (InterruptedException e) {
316 telemetry_reader = null;
318 if (telemetry_logger != null) {
319 AltosDebug.debug("disconnect(): stopping TelemetryLogger");
320 telemetry_logger.stop();
321 telemetry_logger = null;
323 if (altos_link != null) {
324 AltosDebug.debug("disconnect(): stopping AltosDroidLink");
328 telemetry_state.config = null;
330 AltosDebug.debug("disconnect(): send message to clients");
332 if (clients.isEmpty()) {
333 AltosDebug.debug("disconnect(): no clients, terminating");
339 private void start_usb(UsbDevice device) {
340 AltosUsb d = new AltosUsb(this, device, handler);
347 } catch (InterruptedException ie) {
352 private void delete_serial(int serial) {
353 telemetry_state.states.remove((Integer) serial);
354 AltosPreferences.remove_state(serial);
358 private void start_altos_bluetooth(DeviceAddress address, boolean pause) {
359 // Get the BLuetoothDevice object
360 BluetoothDevice device = bluetooth_adapter.getRemoteDevice(address.address);
363 this.address = address;
364 AltosDebug.debug("start_altos_bluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress());
365 altos_link = new AltosBluetooth(device, handler, pause);
366 telemetry_state.connect = TelemetryState.CONNECT_CONNECTING;
367 telemetry_state.address = address;
371 // Timer for receiver battery voltage monitoring
372 Timer receiver_voltage_timer;
374 private void update_receiver_voltage() {
375 if (altos_link != null) {
377 double voltage = altos_link.monitor_battery();
378 AltosDebug.debug("update receiver voltage %g\n", voltage);
379 telemetry_state.receiver_battery = voltage;
380 } catch (InterruptedException ie) {
385 private void stop_receiver_voltage_timer() {
386 if (receiver_voltage_timer != null) {
387 receiver_voltage_timer.cancel();
388 receiver_voltage_timer.purge();
389 receiver_voltage_timer = null;
393 private void start_receiver_voltage_timer() {
394 if (receiver_voltage_timer == null && altos_link.has_monitor_battery()) {
395 receiver_voltage_timer = new Timer();
396 receiver_voltage_timer.scheduleAtFixedRate(new TimerTask() { public void run() {update_receiver_voltage();}}, 1000L, 10000L);
400 private void connected() throws InterruptedException {
401 AltosDebug.debug("connected top");
402 AltosDebug.check_ui("connected\n");
404 if (altos_link == null)
405 throw new InterruptedException("no bluetooth");
406 telemetry_state.config = altos_link.config_data();
407 altos_link.set_radio_frequency(telemetry_state.frequency);
408 altos_link.set_telemetry_rate(telemetry_state.telemetry_rate);
409 } catch (TimeoutException e) {
410 // If this timed out, then we really want to retry it, but
411 // probably safer to just retry the connection from scratch.
412 AltosDebug.debug("connected timeout");
413 if (address != null) {
414 AltosDebug.debug("connected timeout, retrying");
415 start_altos_bluetooth(address, true);
417 handler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
423 AltosDebug.debug("connected bluetooth configured");
424 telemetry_state.connect = TelemetryState.CONNECT_CONNECTED;
425 telemetry_state.address = address;
427 telemetry_reader = new TelemetryReader(altos_link, handler);
428 telemetry_reader.start();
430 AltosDebug.debug("connected TelemetryReader started");
432 telemetry_logger = new TelemetryLogger(this, altos_link);
434 start_receiver_voltage_timer();
436 AltosDebug.debug("Notify UI of connection");
443 public void onCreate() {
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 if (intent != null) {
517 String action = intent.getAction();
519 if (action.equals(AltosDroid.ACTION_BLUETOOTH)) {
520 DeviceAddress address = AltosDroidPreferences.active_device();
521 if (address != null && !address.address.startsWith("USB"))
522 start_altos_bluetooth(address, false);
526 // We want this service to continue running until it is explicitly
527 // stopped, so return sticky.
532 public void onDestroy() {
534 // Stop listening for location updates
535 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
537 // Stop the bluetooth Comms threads
540 // Demote us from the foreground, and cancel the persistent notification.
541 stopForeground(true);
543 // Tell the user we stopped.
544 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
548 public IBinder onBind(Intent intent) {
549 return messenger.getBinder();
553 public void onLocationChanged(Location location) {
554 telemetry_state.location = location;
555 AltosDebug.debug("location changed");
559 public void onStatusChanged(String provider, int status, Bundle extras) {
562 public void onProviderEnabled(String provider) {
565 public void onProviderDisabled(String provider) {