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.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.util.Log;
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_6.*;
51 public class TelemetryService extends Service implements LocationListener {
53 private static final String TAG = "TelemetryService";
54 private static final boolean D = true;
56 static final int MSG_REGISTER_CLIENT = 1;
57 static final int MSG_UNREGISTER_CLIENT = 2;
58 static final int MSG_CONNECT = 3;
59 static final int MSG_CONNECTED = 4;
60 static final int MSG_CONNECT_FAILED = 5;
61 static final int MSG_DISCONNECTED = 6;
62 static final int MSG_TELEMETRY = 7;
63 static final int MSG_SETFREQUENCY = 8;
64 static final int MSG_CRC_ERROR = 9;
65 static final int MSG_SETBAUD = 10;
66 static final int MSG_DISCONNECT = 11;
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 AltosBluetooth altos_bluetooth = 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 // Handler of incoming messages from clients.
90 static class IncomingHandler extends Handler {
91 private final WeakReference<TelemetryService> service;
92 IncomingHandler(TelemetryService s) { service = new WeakReference<TelemetryService>(s); }
95 public void handleMessage(Message msg) {
96 TelemetryService s = service.get();
97 AltosBluetooth bt = null;
102 /* Messages from application */
103 case MSG_REGISTER_CLIENT:
104 s.add_client(msg.replyTo);
106 case MSG_UNREGISTER_CLIENT:
107 s.remove_client(msg.replyTo);
110 if (D) Log.d(TAG, "Connect command received");
111 DeviceAddress address = (DeviceAddress) msg.obj;
112 AltosDroidPreferences.set_active_device(address);
113 s.start_altos_bluetooth(address, false);
116 if (D) Log.d(TAG, "Disconnect command received");
118 s.stop_altos_bluetooth(true);
120 case MSG_SETFREQUENCY:
121 if (D) Log.d(TAG, "MSG_SETFREQUENCY");
122 s.telemetry_state.frequency = (Double) msg.obj;
123 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
125 s.altos_bluetooth.set_radio_frequency(s.telemetry_state.frequency);
126 s.altos_bluetooth.save_frequency();
127 } catch (InterruptedException e) {
128 } catch (TimeoutException e) {
134 if (D) Log.d(TAG, "MSG_SETBAUD");
135 s.telemetry_state.telemetry_rate = (Integer) msg.obj;
136 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
137 s.altos_bluetooth.set_telemetry_rate(s.telemetry_state.telemetry_rate);
138 s.altos_bluetooth.save_telemetry_rate();
144 *Messages from AltosBluetooth
147 Log.d(TAG, "MSG_CONNECTED");
148 bt = (AltosBluetooth) msg.obj;
150 if (bt != s.altos_bluetooth) {
151 if (D) Log.d(TAG, "Stale message");
154 if (D) Log.d(TAG, "Connected to device");
157 } catch (InterruptedException ie) {
160 case MSG_CONNECT_FAILED:
161 Log.d(TAG, "MSG_CONNECT_FAILED");
162 bt = (AltosBluetooth) msg.obj;
164 if (bt != s.altos_bluetooth) {
165 if (D) Log.d(TAG, "Stale message");
168 if (s.address != null) {
169 if (D) Log.d(TAG, "Connection failed... retrying");
170 s.start_altos_bluetooth(s.address, true);
172 s.stop_altos_bluetooth(true);
175 case MSG_DISCONNECTED:
176 Log.d(TAG, "MSG_DISCONNECTED");
177 bt = (AltosBluetooth) msg.obj;
179 if (bt != s.altos_bluetooth) {
180 if (D) Log.d(TAG, "Stale message");
183 if (s.address != null) {
184 if (D) Log.d(TAG, "Connection lost... retrying");
185 s.start_altos_bluetooth(s.address, true);
187 s.stop_altos_bluetooth(true);
192 * Messages from TelemetryReader
195 s.telemetry_state.state = (AltosState) msg.obj;
196 if (s.telemetry_state.state != null) {
197 if (D) Log.d(TAG, "Save state");
198 AltosPreferences.set_state(0, s.telemetry_state.state, null);
200 if (D) Log.d(TAG, "MSG_TELEMETRY");
204 // forward crc error messages
205 s.telemetry_state.crc_errors = (Integer) msg.obj;
206 if (D) Log.d(TAG, "MSG_CRC_ERROR");
210 super.handleMessage(msg);
215 /* Construct the message to deliver to clients
217 private Message message() {
218 if (telemetry_state == null)
219 Log.d(TAG, "telemetry_state null!");
220 if (telemetry_state.state == null)
221 Log.d(TAG, "telemetry_state.state null!");
222 return Message.obtain(null, AltosDroid.MSG_STATE, telemetry_state);
225 /* A new friend has connected
227 private void add_client(Messenger client) {
230 if (D) Log.d(TAG, "Client bound to service");
232 /* On connect, send the current state to the new client
234 send_to_client(client, message());
236 /* If we've got an address from a previous session, then
237 * go ahead and try to reconnect to the device
239 if (address != null && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
240 if (D) Log.d(TAG, "Reconnecting now...");
241 start_altos_bluetooth(address, false);
245 /* A client has disconnected, clean up
247 private void remove_client(Messenger client) {
248 clients.remove(client);
249 if (D) Log.d(TAG, "Client unbound from service");
251 /* When the list of clients is empty, stop the service if
252 * we have no current telemetry source
255 if (clients.isEmpty() && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
256 if (!D) Log.d(TAG, "No clients, no connection. Stopping\n");
261 private void send_to_client(Messenger client, Message m) {
263 if (D) Log.d(TAG, String.format("Send message to client %s", client.toString()));
265 } catch (RemoteException e) {
266 if (D) Log.e(TAG, String.format("Client %s disappeared", client.toString()));
267 remove_client(client);
271 private void send_to_clients() {
272 Message m = message();
273 if (D) Log.d(TAG, String.format("Send message to %d clients", clients.size()));
274 for (Messenger client : clients)
275 send_to_client(client, m);
278 private void stop_altos_bluetooth(boolean notify) {
279 if (D) Log.d(TAG, "stop_altos_bluetooth(): begin");
280 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
281 telemetry_state.address = null;
283 if (altos_bluetooth != null)
284 altos_bluetooth.closing();
286 if (telemetry_reader != null) {
287 if (D) Log.d(TAG, "stop_altos_bluetooth(): stopping TelemetryReader");
288 telemetry_reader.interrupt();
290 telemetry_reader.join();
291 } catch (InterruptedException e) {
293 telemetry_reader = null;
295 if (telemetry_logger != null) {
296 if (D) Log.d(TAG, "stop_altos_bluetooth(): stopping TelemetryLogger");
297 telemetry_logger.stop();
298 telemetry_logger = null;
300 if (altos_bluetooth != null) {
301 if (D) Log.d(TAG, "stop_altos_bluetooth(): stopping AltosBluetooth");
302 altos_bluetooth.close();
303 altos_bluetooth = null;
305 telemetry_state.config = null;
307 if (D) Log.d(TAG, "stop_altos_bluetooth(): send message to clients");
309 if (clients.isEmpty()) {
310 if (D) Log.d(TAG, "stop_altos_bluetooth(): no clients, terminating");
316 private void start_altos_bluetooth(DeviceAddress address, boolean pause) {
317 // Get the BLuetoothDevice object
318 BluetoothDevice device = bluetooth_adapter.getRemoteDevice(address.address);
320 stop_altos_bluetooth(false);
324 } catch (InterruptedException e) {
327 this.address = address;
328 if (D) Log.d(TAG, String.format("start_altos_bluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress()));
329 altos_bluetooth = new AltosBluetooth(device, handler);
330 telemetry_state.connect = TelemetryState.CONNECT_CONNECTING;
331 telemetry_state.address = address;
335 private void connected() throws InterruptedException {
336 if (D) Log.d(TAG, "connected top");
338 if (altos_bluetooth == null)
339 throw new InterruptedException("no bluetooth");
340 telemetry_state.config = altos_bluetooth.config_data();
341 altos_bluetooth.set_radio_frequency(telemetry_state.frequency);
342 altos_bluetooth.set_telemetry_rate(telemetry_state.telemetry_rate);
343 } catch (TimeoutException e) {
344 // If this timed out, then we really want to retry it, but
345 // probably safer to just retry the connection from scratch.
346 if (D) Log.d(TAG, "connected timeout");
347 if (address != null) {
348 if (D) Log.d(TAG, "connected timeout, retrying");
349 start_altos_bluetooth(address, true);
351 handler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
352 stop_altos_bluetooth(true);
357 if (D) Log.d(TAG, "connected bluetooth configured");
358 telemetry_state.connect = TelemetryState.CONNECT_CONNECTED;
359 telemetry_state.address = address;
361 telemetry_reader = new TelemetryReader(altos_bluetooth, handler, telemetry_state.state);
362 telemetry_reader.start();
364 if (D) Log.d(TAG, "connected TelemetryReader started");
366 telemetry_logger = new TelemetryLogger(this, altos_bluetooth);
368 if (D) Log.d(TAG, "Notify UI of connection");
375 public void onCreate() {
376 // Get local Bluetooth adapter
377 bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
379 // If the adapter is null, then Bluetooth is not supported
380 if (bluetooth_adapter == null) {
381 Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
384 // Initialise preferences
385 AltosDroidPreferences.init(this);
387 telemetry_state = new TelemetryState();
389 // Create a reference to the NotificationManager so that we can update our notifcation text later
390 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
392 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
393 telemetry_state.address = null;
395 AltosSavedState saved_state = AltosPreferences.state(0);
397 if (saved_state != null) {
398 if (D) Log.d(TAG, String.format("recovered old state flight %d\n", saved_state.state.flight));
399 telemetry_state.state = saved_state.state;
402 // Listen for GPS and Network position updates
403 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
405 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
407 DeviceAddress address = AltosDroidPreferences.active_device();
409 start_altos_bluetooth(address, false);
413 public int onStartCommand(Intent intent, int flags, int startId) {
414 Log.i("TelemetryService", "Received start id " + startId + ": " + intent);
416 CharSequence text = getText(R.string.telemetry_service_started);
418 // Create notification to be displayed while the service runs
419 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
421 // The PendingIntent to launch our activity if the user selects this notification
422 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
423 new Intent(this, AltosDroid.class), 0);
425 // Set the info for the views that show in the notification panel.
426 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
428 // Set the notification to be in the "Ongoing" section.
429 notification.flags |= Notification.FLAG_ONGOING_EVENT;
431 // Move us into the foreground.
432 startForeground(NOTIFICATION, notification);
434 // We want this service to continue running until it is explicitly
435 // stopped, so return sticky.
440 public void onDestroy() {
442 // Stop listening for location updates
443 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
445 // Stop the bluetooth Comms threads
446 stop_altos_bluetooth(true);
448 // Demote us from the foreground, and cancel the persistent notification.
449 stopForeground(true);
451 // Tell the user we stopped.
452 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
456 public IBinder onBind(Intent intent) {
457 return messenger.getBinder();
461 public void onLocationChanged(Location location) {
462 telemetry_state.location = location;
463 if (D) Log.d(TAG, "location changed");
467 public void onStatusChanged(String provider, int status, Bundle extras) {
470 public void onProviderEnabled(String provider) {
473 public void onProviderDisabled(String provider) {