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.ArrayList;
22 import java.util.concurrent.TimeoutException;
23 import java.util.Timer;
24 import java.util.TimerTask;
26 import android.app.Notification;
27 //import android.app.NotificationManager;
28 import android.app.PendingIntent;
29 import android.app.Service;
30 import android.bluetooth.BluetoothDevice;
31 import android.bluetooth.BluetoothAdapter;
32 import android.hardware.usb.*;
33 import android.content.Intent;
34 import android.content.Context;
35 import android.os.Bundle;
36 import android.os.IBinder;
37 import android.os.Handler;
38 import android.os.Message;
39 import android.os.Messenger;
40 import android.os.RemoteException;
41 import android.os.Looper;
42 import android.util.Log;
43 import android.widget.Toast;
44 import android.location.Location;
45 import android.location.LocationManager;
46 import android.location.LocationListener;
47 import android.location.Criteria;
49 import org.altusmetrum.altoslib_7.*;
52 public class TelemetryService extends Service implements LocationListener {
54 private static final String TAG = "TelemetryService";
55 private static final boolean D = true;
57 static final int MSG_REGISTER_CLIENT = 1;
58 static final int MSG_UNREGISTER_CLIENT = 2;
59 static final int MSG_CONNECT = 3;
60 static final int MSG_OPEN_USB = 4;
61 static final int MSG_CONNECTED = 5;
62 static final int MSG_CONNECT_FAILED = 6;
63 static final int MSG_DISCONNECTED = 7;
64 static final int MSG_TELEMETRY = 8;
65 static final int MSG_SETFREQUENCY = 9;
66 static final int MSG_CRC_ERROR = 10;
67 static final int MSG_SETBAUD = 11;
68 static final int MSG_DISCONNECT = 12;
70 // Unique Identification Number for the Notification.
71 // We use it on Notification start, and to cancel it.
72 private int NOTIFICATION = R.string.telemetry_service_label;
73 //private NotificationManager mNM;
75 ArrayList<Messenger> clients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
76 final Handler handler = new IncomingHandler(this);
77 final Messenger messenger = new Messenger(handler); // Target we publish for clients to send messages to IncomingHandler.
79 // Name of the connected device
80 DeviceAddress address;
81 private AltosDroidLink altos_link = null;
82 private TelemetryReader telemetry_reader = null;
83 private TelemetryLogger telemetry_logger = null;
85 // Local Bluetooth adapter
86 private BluetoothAdapter bluetooth_adapter = null;
88 // Last data seen; send to UI when it starts
89 private TelemetryState telemetry_state;
91 // Handler of incoming messages from clients.
92 static class IncomingHandler extends Handler {
93 private final WeakReference<TelemetryService> service;
94 IncomingHandler(TelemetryService s) { service = new WeakReference<TelemetryService>(s); }
97 public void handleMessage(Message msg) {
98 TelemetryService s = service.get();
99 AltosDroidLink bt = null;
104 /* Messages from application */
105 case MSG_REGISTER_CLIENT:
106 s.add_client(msg.replyTo);
108 case MSG_UNREGISTER_CLIENT:
109 s.remove_client(msg.replyTo);
112 if (D) Log.d(TAG, "Connect command received");
113 DeviceAddress address = (DeviceAddress) msg.obj;
114 AltosDroidPreferences.set_active_device(address);
115 s.start_altos_bluetooth(address, false);
118 if (D) Log.d(TAG, "Open USB command received");
119 UsbDevice device = (UsbDevice) msg.obj;
123 if (D) Log.d(TAG, "Disconnect command received");
127 case MSG_SETFREQUENCY:
128 if (D) Log.d(TAG, "MSG_SETFREQUENCY");
129 s.telemetry_state.frequency = (Double) msg.obj;
130 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
132 s.altos_link.set_radio_frequency(s.telemetry_state.frequency);
133 s.altos_link.save_frequency();
134 } catch (InterruptedException e) {
135 } catch (TimeoutException e) {
141 if (D) Log.d(TAG, "MSG_SETBAUD");
142 s.telemetry_state.telemetry_rate = (Integer) msg.obj;
143 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
144 s.altos_link.set_telemetry_rate(s.telemetry_state.telemetry_rate);
145 s.altos_link.save_telemetry_rate();
151 *Messages from AltosBluetooth
154 Log.d(TAG, "MSG_CONNECTED");
155 bt = (AltosDroidLink) msg.obj;
157 if (bt != s.altos_link) {
158 if (D) Log.d(TAG, "Stale message");
161 if (D) Log.d(TAG, "Connected to device");
164 } catch (InterruptedException ie) {
167 case MSG_CONNECT_FAILED:
168 Log.d(TAG, "MSG_CONNECT_FAILED");
169 bt = (AltosDroidLink) msg.obj;
171 if (bt != s.altos_link) {
172 if (D) Log.d(TAG, "Stale message");
175 if (s.address != null) {
176 if (D) Log.d(TAG, "Connection failed... retrying");
177 s.start_altos_bluetooth(s.address, true);
182 case MSG_DISCONNECTED:
184 /* This can be sent by either AltosDroidLink or TelemetryReader */
185 Log.d(TAG, "MSG_DISCONNECTED");
186 bt = (AltosDroidLink) msg.obj;
188 if (bt != s.altos_link) {
189 if (D) Log.d(TAG, "Stale message");
192 if (s.address != null) {
193 if (D) Log.d(TAG, "Connection lost... retrying");
194 s.start_altos_bluetooth(s.address, true);
201 * Messages from TelemetryReader
204 s.telemetry_state.state = (AltosState) msg.obj;
205 if (s.telemetry_state.state != null) {
206 if (D) Log.d(TAG, "Save state");
207 AltosPreferences.set_state(0, s.telemetry_state.state, null);
209 if (D) Log.d(TAG, "MSG_TELEMETRY");
213 // forward crc error messages
214 s.telemetry_state.crc_errors = (Integer) msg.obj;
215 if (D) Log.d(TAG, "MSG_CRC_ERROR");
219 super.handleMessage(msg);
224 /* Construct the message to deliver to clients
226 private Message message() {
227 if (telemetry_state == null)
228 Log.d(TAG, "telemetry_state null!");
229 if (telemetry_state.state == null)
230 Log.d(TAG, "telemetry_state.state null!");
231 return Message.obtain(null, AltosDroid.MSG_STATE, telemetry_state);
234 /* A new friend has connected
236 private void add_client(Messenger client) {
239 if (D) Log.d(TAG, "Client bound to service");
241 /* On connect, send the current state to the new client
243 send_to_client(client, message());
245 /* If we've got an address from a previous session, then
246 * go ahead and try to reconnect to the device
248 if (address != null && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
249 if (D) Log.d(TAG, "Reconnecting now...");
250 start_altos_bluetooth(address, false);
254 /* A client has disconnected, clean up
256 private void remove_client(Messenger client) {
257 clients.remove(client);
258 if (D) Log.d(TAG, "Client unbound from service");
260 /* When the list of clients is empty, stop the service if
261 * we have no current telemetry source
264 if (clients.isEmpty() && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
265 if (!D) Log.d(TAG, "No clients, no connection. Stopping\n");
270 private void send_to_client(Messenger client, Message m) {
272 if (D) Log.d(TAG, String.format("Send message to client %s", client.toString()));
274 } catch (RemoteException e) {
275 if (D) Log.e(TAG, String.format("Client %s disappeared", client.toString()));
276 remove_client(client);
280 private void send_to_clients() {
281 Message m = message();
282 if (D) Log.d(TAG, String.format("Send message to %d clients", clients.size()));
283 for (Messenger client : clients)
284 send_to_client(client, m);
287 private void disconnect(boolean notify) {
288 if (D) Log.d(TAG, "disconnect(): begin");
290 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
291 telemetry_state.address = null;
293 if (altos_link != null)
294 altos_link.closing();
296 if (telemetry_reader != null) {
297 if (D) Log.d(TAG, "disconnect(): stopping TelemetryReader");
298 telemetry_reader.interrupt();
300 telemetry_reader.join();
301 } catch (InterruptedException e) {
303 telemetry_reader = null;
305 if (telemetry_logger != null) {
306 if (D) Log.d(TAG, "disconnect(): stopping TelemetryLogger");
307 telemetry_logger.stop();
308 telemetry_logger = null;
310 if (altos_link != null) {
311 if (D) Log.d(TAG, "disconnect(): stopping AltosDroidLink");
315 telemetry_state.config = null;
317 if (D) Log.d(TAG, "disconnect(): send message to clients");
319 if (clients.isEmpty()) {
320 if (D) Log.d(TAG, "disconnect(): no clients, terminating");
326 private void start_usb(UsbDevice device) {
327 AltosUsb d = new AltosUsb(this, device, handler);
334 } catch (InterruptedException ie) {
339 private void start_altos_bluetooth(DeviceAddress address, boolean pause) {
340 // Get the BLuetoothDevice object
341 BluetoothDevice device = bluetooth_adapter.getRemoteDevice(address.address);
344 this.address = address;
345 if (D) Log.d(TAG, String.format("start_altos_bluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress()));
346 altos_link = new AltosBluetooth(device, handler);
347 telemetry_state.connect = TelemetryState.CONNECT_CONNECTING;
348 telemetry_state.address = address;
352 private void connected() throws InterruptedException {
353 if (D) Log.d(TAG, "connected top");
355 if (altos_link == null)
356 throw new InterruptedException("no bluetooth");
357 telemetry_state.config = altos_link.config_data();
358 altos_link.set_radio_frequency(telemetry_state.frequency);
359 altos_link.set_telemetry_rate(telemetry_state.telemetry_rate);
360 } catch (TimeoutException e) {
361 // If this timed out, then we really want to retry it, but
362 // probably safer to just retry the connection from scratch.
363 if (D) Log.d(TAG, "connected timeout");
364 if (address != null) {
365 if (D) Log.d(TAG, "connected timeout, retrying");
366 start_altos_bluetooth(address, true);
368 handler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
374 if (D) Log.d(TAG, "connected bluetooth configured");
375 telemetry_state.connect = TelemetryState.CONNECT_CONNECTED;
376 telemetry_state.address = address;
378 telemetry_reader = new TelemetryReader(altos_link, handler, telemetry_state.state);
379 telemetry_reader.start();
381 if (D) Log.d(TAG, "connected TelemetryReader started");
383 telemetry_logger = new TelemetryLogger(this, altos_link);
385 if (D) Log.d(TAG, "Notify UI of connection");
392 public void onCreate() {
393 // Get local Bluetooth adapter
394 bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
396 // If the adapter is null, then Bluetooth is not supported
397 if (bluetooth_adapter == null) {
398 Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
401 // Initialise preferences
402 AltosDroidPreferences.init(this);
404 telemetry_state = new TelemetryState();
406 // Create a reference to the NotificationManager so that we can update our notifcation text later
407 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
409 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
410 telemetry_state.address = null;
412 AltosSavedState saved_state = AltosPreferences.state(0);
414 if (saved_state != null) {
415 if (D) Log.d(TAG, String.format("recovered old state flight %d\n", saved_state.state.flight));
416 telemetry_state.state = saved_state.state;
419 // Listen for GPS and Network position updates
420 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
422 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
426 public int onStartCommand(Intent intent, int flags, int startId) {
427 Log.i("TelemetryService", "Received start id " + startId + ": " + intent);
429 CharSequence text = getText(R.string.telemetry_service_started);
431 // Create notification to be displayed while the service runs
432 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
434 // The PendingIntent to launch our activity if the user selects this notification
435 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
436 new Intent(this, AltosDroid.class), 0);
438 // Set the info for the views that show in the notification panel.
439 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
441 // Set the notification to be in the "Ongoing" section.
442 notification.flags |= Notification.FLAG_ONGOING_EVENT;
444 // Move us into the foreground.
445 startForeground(NOTIFICATION, notification);
447 if (intent != null) {
448 String action = intent.getAction();
450 if (action.equals(AltosDroid.ACTION_BLUETOOTH)) {
451 DeviceAddress address = AltosDroidPreferences.active_device();
452 if (address != null && !address.address.startsWith("USB"))
453 start_altos_bluetooth(address, false);
457 // We want this service to continue running until it is explicitly
458 // stopped, so return sticky.
463 public void onDestroy() {
465 // Stop listening for location updates
466 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
468 // Stop the bluetooth Comms threads
471 // Demote us from the foreground, and cancel the persistent notification.
472 stopForeground(true);
474 // Tell the user we stopped.
475 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
479 public IBinder onBind(Intent intent) {
480 return messenger.getBinder();
484 public void onLocationChanged(Location location) {
485 telemetry_state.location = location;
486 if (D) Log.d(TAG, "location changed");
490 public void onStatusChanged(String provider, int status, Bundle extras) {
493 public void onProviderEnabled(String provider) {
496 public void onProviderDisabled(String provider) {