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.widget.Toast;
43 import android.location.Location;
44 import android.location.LocationManager;
45 import android.location.LocationListener;
46 import android.location.Criteria;
48 import org.altusmetrum.altoslib_7.*;
51 public class TelemetryService extends Service implements LocationListener {
53 static final int MSG_REGISTER_CLIENT = 1;
54 static final int MSG_UNREGISTER_CLIENT = 2;
55 static final int MSG_CONNECT = 3;
56 static final int MSG_OPEN_USB = 4;
57 static final int MSG_CONNECTED = 5;
58 static final int MSG_CONNECT_FAILED = 6;
59 static final int MSG_DISCONNECTED = 7;
60 static final int MSG_TELEMETRY = 8;
61 static final int MSG_SETFREQUENCY = 9;
62 static final int MSG_CRC_ERROR = 10;
63 static final int MSG_SETBAUD = 11;
64 static final int MSG_DISCONNECT = 12;
66 // Unique Identification Number for the Notification.
67 // We use it on Notification start, and to cancel it.
68 private int NOTIFICATION = R.string.telemetry_service_label;
69 //private NotificationManager mNM;
71 ArrayList<Messenger> clients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
72 final Handler handler = new IncomingHandler(this);
73 final Messenger messenger = new Messenger(handler); // Target we publish for clients to send messages to IncomingHandler.
75 // Name of the connected device
76 DeviceAddress address;
77 private AltosDroidLink altos_link = null;
78 private TelemetryReader telemetry_reader = null;
79 private TelemetryLogger telemetry_logger = null;
81 // Local Bluetooth adapter
82 private BluetoothAdapter bluetooth_adapter = null;
84 // Last data seen; send to UI when it starts
85 private TelemetryState telemetry_state;
87 // Handler of incoming messages from clients.
88 static class IncomingHandler extends Handler {
89 private final WeakReference<TelemetryService> service;
90 IncomingHandler(TelemetryService s) { service = new WeakReference<TelemetryService>(s); }
93 public void handleMessage(Message msg) {
94 TelemetryService s = service.get();
95 AltosDroidLink bt = null;
100 /* Messages from application */
101 case MSG_REGISTER_CLIENT:
102 s.add_client(msg.replyTo);
104 case MSG_UNREGISTER_CLIENT:
105 s.remove_client(msg.replyTo);
108 AltosDebug.debug("Connect command received");
109 DeviceAddress address = (DeviceAddress) msg.obj;
110 AltosDroidPreferences.set_active_device(address);
111 s.start_altos_bluetooth(address, false);
114 AltosDebug.debug("Open USB command received");
115 UsbDevice device = (UsbDevice) msg.obj;
119 AltosDebug.debug("Disconnect command received");
123 case MSG_SETFREQUENCY:
124 AltosDebug.debug("MSG_SETFREQUENCY");
125 s.telemetry_state.frequency = (Double) msg.obj;
126 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
128 s.altos_link.set_radio_frequency(s.telemetry_state.frequency);
129 s.altos_link.save_frequency();
130 } catch (InterruptedException e) {
131 } catch (TimeoutException e) {
137 AltosDebug.debug("MSG_SETBAUD");
138 s.telemetry_state.telemetry_rate = (Integer) msg.obj;
139 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
140 s.altos_link.set_telemetry_rate(s.telemetry_state.telemetry_rate);
141 s.altos_link.save_telemetry_rate();
147 *Messages from AltosBluetooth
150 AltosDebug.debug("MSG_CONNECTED");
151 bt = (AltosDroidLink) msg.obj;
153 if (bt != s.altos_link) {
154 AltosDebug.debug("Stale message");
157 AltosDebug.debug("Connected to device");
160 } catch (InterruptedException ie) {
163 case MSG_CONNECT_FAILED:
164 AltosDebug.debug("MSG_CONNECT_FAILED");
165 bt = (AltosDroidLink) msg.obj;
167 if (bt != s.altos_link) {
168 AltosDebug.debug("Stale message");
171 if (s.address != null) {
172 AltosDebug.debug("Connection failed... retrying");
173 s.start_altos_bluetooth(s.address, true);
178 case MSG_DISCONNECTED:
180 /* This can be sent by either AltosDroidLink or TelemetryReader */
181 AltosDebug.debug("MSG_DISCONNECTED");
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 lost... retrying");
190 s.start_altos_bluetooth(s.address, true);
197 * Messages from TelemetryReader
200 s.telemetry_state.state = (AltosState) msg.obj;
201 if (s.telemetry_state.state != null) {
202 AltosDebug.debug("Save state");
203 AltosPreferences.set_state(0, s.telemetry_state.state, null);
205 AltosDebug.debug("MSG_TELEMETRY");
209 // forward crc error messages
210 s.telemetry_state.crc_errors = (Integer) msg.obj;
211 AltosDebug.debug("MSG_CRC_ERROR");
215 super.handleMessage(msg);
220 /* Construct the message to deliver to clients
222 private Message message() {
223 if (telemetry_state == null)
224 AltosDebug.debug("telemetry_state null!");
225 if (telemetry_state.state == null)
226 AltosDebug.debug("telemetry_state.state null!");
227 return Message.obtain(null, AltosDroid.MSG_STATE, telemetry_state);
230 /* A new friend has connected
232 private void add_client(Messenger client) {
235 AltosDebug.debug("Client bound to service");
237 /* On connect, send the current state to the new client
239 send_to_client(client, message());
241 /* If we've got an address from a previous session, then
242 * go ahead and try to reconnect to the device
244 if (address != null && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
245 AltosDebug.debug("Reconnecting now...");
246 start_altos_bluetooth(address, false);
250 /* A client has disconnected, clean up
252 private void remove_client(Messenger client) {
253 clients.remove(client);
254 AltosDebug.debug("Client unbound from service");
256 /* When the list of clients is empty, stop the service if
257 * we have no current telemetry source
260 if (clients.isEmpty() && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
261 AltosDebug.debug("No clients, no connection. Stopping\n");
266 private void send_to_client(Messenger client, Message m) {
268 AltosDebug.debug("Send message to client %s", client.toString());
270 } catch (RemoteException e) {
271 AltosDebug.error("Client %s disappeared", client.toString());
272 remove_client(client);
276 private void send_to_clients() {
277 Message m = message();
278 AltosDebug.debug("Send message to %d clients", clients.size());
279 for (Messenger client : clients)
280 send_to_client(client, m);
283 private void disconnect(boolean notify) {
284 AltosDebug.debug("disconnect(): begin");
286 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
287 telemetry_state.address = null;
289 if (altos_link != null)
290 altos_link.closing();
292 if (telemetry_reader != null) {
293 AltosDebug.debug("disconnect(): stopping TelemetryReader");
294 telemetry_reader.interrupt();
296 telemetry_reader.join();
297 } catch (InterruptedException e) {
299 telemetry_reader = null;
301 if (telemetry_logger != null) {
302 AltosDebug.debug("disconnect(): stopping TelemetryLogger");
303 telemetry_logger.stop();
304 telemetry_logger = null;
306 if (altos_link != null) {
307 AltosDebug.debug("disconnect(): stopping AltosDroidLink");
311 telemetry_state.config = null;
313 AltosDebug.debug("disconnect(): send message to clients");
315 if (clients.isEmpty()) {
316 AltosDebug.debug("disconnect(): no clients, terminating");
322 private void start_usb(UsbDevice device) {
323 AltosUsb d = new AltosUsb(this, device, handler);
330 } catch (InterruptedException ie) {
335 private void start_altos_bluetooth(DeviceAddress address, boolean pause) {
336 // Get the BLuetoothDevice object
337 AltosDebug.check_ui("start_altos_bluetooth\n");
338 BluetoothDevice device = bluetooth_adapter.getRemoteDevice(address.address);
341 this.address = address;
342 AltosDebug.debug("start_altos_bluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress());
343 altos_link = new AltosBluetooth(device, handler, pause);
344 telemetry_state.connect = TelemetryState.CONNECT_CONNECTING;
345 telemetry_state.address = address;
349 private void connected() throws InterruptedException {
350 AltosDebug.debug("connected top");
351 AltosDebug.check_ui("connected\n");
353 if (altos_link == null)
354 throw new InterruptedException("no bluetooth");
355 telemetry_state.config = altos_link.config_data();
356 altos_link.set_radio_frequency(telemetry_state.frequency);
357 altos_link.set_telemetry_rate(telemetry_state.telemetry_rate);
358 } catch (TimeoutException e) {
359 // If this timed out, then we really want to retry it, but
360 // probably safer to just retry the connection from scratch.
361 AltosDebug.debug("connected timeout");
362 if (address != null) {
363 AltosDebug.debug("connected timeout, retrying");
364 start_altos_bluetooth(address, true);
366 handler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
372 AltosDebug.debug("connected bluetooth configured");
373 telemetry_state.connect = TelemetryState.CONNECT_CONNECTED;
374 telemetry_state.address = address;
376 telemetry_reader = new TelemetryReader(altos_link, handler, telemetry_state.state);
377 telemetry_reader.start();
379 AltosDebug.debug("connected TelemetryReader started");
381 telemetry_logger = new TelemetryLogger(this, altos_link);
383 AltosDebug.debug("Notify UI of connection");
390 public void onCreate() {
391 // Get local Bluetooth adapter
392 bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
394 // If the adapter is null, then Bluetooth is not supported
395 if (bluetooth_adapter == null) {
396 Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
399 // Initialise preferences
400 AltosDroidPreferences.init(this);
402 telemetry_state = new TelemetryState();
404 // Create a reference to the NotificationManager so that we can update our notifcation text later
405 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
407 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
408 telemetry_state.address = null;
410 AltosSavedState saved_state = AltosPreferences.state(0);
412 if (saved_state != null) {
413 AltosDebug.debug("recovered old state flight %d\n", saved_state.state.flight);
414 telemetry_state.state = saved_state.state;
417 // Listen for GPS and Network position updates
418 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
420 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
424 public int onStartCommand(Intent intent, int flags, int startId) {
425 AltosDebug.debug("Received start id %d: %s", startId, intent);
427 CharSequence text = getText(R.string.telemetry_service_started);
429 // Create notification to be displayed while the service runs
430 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
432 // The PendingIntent to launch our activity if the user selects this notification
433 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
434 new Intent(this, AltosDroid.class), 0);
436 // Set the info for the views that show in the notification panel.
437 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
439 // Set the notification to be in the "Ongoing" section.
440 notification.flags |= Notification.FLAG_ONGOING_EVENT;
442 // Move us into the foreground.
443 startForeground(NOTIFICATION, notification);
445 if (intent != null) {
446 String action = intent.getAction();
448 if (action.equals(AltosDroid.ACTION_BLUETOOTH)) {
449 DeviceAddress address = AltosDroidPreferences.active_device();
450 if (address != null && !address.address.startsWith("USB"))
451 start_altos_bluetooth(address, false);
455 // We want this service to continue running until it is explicitly
456 // stopped, so return sticky.
461 public void onDestroy() {
463 // Stop listening for location updates
464 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
466 // Stop the bluetooth Comms threads
469 // Demote us from the foreground, and cancel the persistent notification.
470 stopForeground(true);
472 // Tell the user we stopped.
473 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
477 public IBinder onBind(Intent intent) {
478 return messenger.getBinder();
482 public void onLocationChanged(Location location) {
483 telemetry_state.location = location;
484 AltosDebug.debug("location changed");
488 public void onStatusChanged(String provider, int status, Bundle extras) {
491 public void onProviderEnabled(String provider) {
494 public void onProviderDisabled(String provider) {