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;
67 // Unique Identification Number for the Notification.
68 // We use it on Notification start, and to cancel it.
69 private int NOTIFICATION = R.string.telemetry_service_label;
70 //private NotificationManager mNM;
72 ArrayList<Messenger> clients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
73 final Handler handler = new IncomingHandler(this);
74 final Messenger messenger = new Messenger(handler); // Target we publish for clients to send messages to IncomingHandler.
76 // Name of the connected device
77 DeviceAddress address;
78 private AltosBluetooth altos_bluetooth = null;
79 private TelemetryReader telemetry_reader = null;
80 private TelemetryLogger telemetry_logger = null;
82 // Local Bluetooth adapter
83 private BluetoothAdapter bluetooth_adapter = null;
85 // Last data seen; send to UI when it starts
86 private TelemetryState telemetry_state;
88 // Handler of incoming messages from clients.
89 static class IncomingHandler extends Handler {
90 private final WeakReference<TelemetryService> service;
91 IncomingHandler(TelemetryService s) { service = new WeakReference<TelemetryService>(s); }
94 public void handleMessage(Message msg) {
95 TelemetryService s = service.get();
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 if (D) Log.d(TAG, "Connect command received");
109 DeviceAddress address = (DeviceAddress) msg.obj;
110 AltosDroidPreferences.set_active_device(address);
111 s.start_altos_bluetooth(address);
113 case MSG_SETFREQUENCY:
114 if (D) Log.d(TAG, "MSG_SETFREQUENCY");
115 s.telemetry_state.frequency = (Double) msg.obj;
116 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
118 s.altos_bluetooth.set_radio_frequency(s.telemetry_state.frequency);
119 s.altos_bluetooth.save_frequency();
120 } catch (InterruptedException e) {
121 } catch (TimeoutException e) {
127 if (D) Log.d(TAG, "MSG_SETBAUD");
128 s.telemetry_state.telemetry_rate = (Integer) msg.obj;
129 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
130 s.altos_bluetooth.set_telemetry_rate(s.telemetry_state.telemetry_rate);
131 s.altos_bluetooth.save_telemetry_rate();
137 *Messages from AltosBluetooth
140 if (D) Log.d(TAG, "Connected to device");
143 } catch (InterruptedException ie) {
146 case MSG_CONNECT_FAILED:
147 if (s.address != null && !s.clients.isEmpty()) {
148 if (D) Log.d(TAG, "Connection failed... retrying");
149 s.start_altos_bluetooth(s.address);
151 s.stop_altos_bluetooth(true);
154 case MSG_DISCONNECTED:
155 Log.d(TAG, "MSG_DISCONNECTED");
156 if (s.address != null && !s.clients.isEmpty()) {
157 if (D) Log.d(TAG, "Connection lost... retrying");
158 s.start_altos_bluetooth(s.address);
160 s.stop_altos_bluetooth(true);
165 * Messages from TelemetryReader
168 s.telemetry_state.state = (AltosState) msg.obj;
169 if (s.telemetry_state.state != null) {
170 if (D) Log.d(TAG, "Save state");
171 AltosPreferences.set_state(0, s.telemetry_state.state, null);
173 if (D) Log.d(TAG, "MSG_TELEMETRY");
177 // forward crc error messages
178 s.telemetry_state.crc_errors = (Integer) msg.obj;
179 if (D) Log.d(TAG, "MSG_CRC_ERROR");
183 super.handleMessage(msg);
188 /* Construct the message to deliver to clients
190 private Message message() {
191 if (telemetry_state == null)
192 Log.d(TAG, "telemetry_state null!");
193 if (telemetry_state.state == null)
194 Log.d(TAG, "telemetry_state.state null!");
195 return Message.obtain(null, AltosDroid.MSG_STATE, telemetry_state);
198 /* A new friend has connected
200 private void add_client(Messenger client) {
203 if (D) Log.d(TAG, "Client bound to service");
205 /* On connect, send the current state to the new client
207 send_to_client(client, message());
209 /* If we've got an address from a previous session, then
210 * go ahead and try to reconnect to the device
212 if (address != null && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
213 if (D) Log.d(TAG, "Reconnecting now...");
214 start_altos_bluetooth(address);
218 /* A client has disconnected, clean up
220 private void remove_client(Messenger client) {
221 clients.remove(client);
222 if (D) Log.d(TAG, "Client unbound from service");
224 /* When the list of clients is empty, stop the service if
225 * we have no current telemetry source
228 if (clients.isEmpty() && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
229 if (!D) Log.d(TAG, "No clients, no connection. Stopping\n");
234 private void send_to_client(Messenger client, Message m) {
236 if (D) Log.d(TAG, String.format("Send message to client %s", client.toString()));
238 } catch (RemoteException e) {
239 if (D) Log.e(TAG, String.format("Client %s disappeared", client.toString()));
240 remove_client(client);
244 private void send_to_clients() {
245 Message m = message();
246 if (D) Log.d(TAG, String.format("Send message to %d clients", clients.size()));
247 for (Messenger client : clients)
248 send_to_client(client, m);
251 private void stop_altos_bluetooth(boolean notify) {
252 if (D) Log.d(TAG, "stop_altos_bluetooth(): begin");
253 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
254 telemetry_state.address = null;
256 if (altos_bluetooth != null)
257 altos_bluetooth.closing();
259 if (telemetry_reader != null) {
260 if (D) Log.d(TAG, "stop_altos_bluetooth(): stopping TelemetryReader");
261 telemetry_reader.interrupt();
263 telemetry_reader.join();
264 } catch (InterruptedException e) {
266 telemetry_reader = null;
268 if (telemetry_logger != null) {
269 if (D) Log.d(TAG, "stop_altos_bluetooth(): stopping TelemetryLogger");
270 telemetry_logger.stop();
271 telemetry_logger = null;
273 if (altos_bluetooth != null) {
274 if (D) Log.d(TAG, "stop_altos_bluetooth(): stopping AltosBluetooth");
275 altos_bluetooth.close();
276 altos_bluetooth = null;
278 telemetry_state.config = null;
280 if (D) Log.d(TAG, "stop_altos_bluetooth(): send message to clients");
282 if (clients.isEmpty()) {
283 if (D) Log.d(TAG, "stop_altos_bluetooth(): no clients, terminating");
289 private void start_altos_bluetooth(DeviceAddress address) {
290 // Get the BLuetoothDevice object
291 BluetoothDevice device = bluetooth_adapter.getRemoteDevice(address.address);
293 stop_altos_bluetooth(false);
294 this.address = address;
295 if (D) Log.d(TAG, String.format("start_altos_bluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress()));
296 altos_bluetooth = new AltosBluetooth(device, handler);
297 telemetry_state.connect = TelemetryState.CONNECT_CONNECTING;
298 telemetry_state.address = address;
302 private void connected() throws InterruptedException {
303 if (D) Log.d(TAG, "connected top");
305 if (altos_bluetooth == null)
306 throw new InterruptedException("no bluetooth");
307 telemetry_state.config = altos_bluetooth.config_data();
308 altos_bluetooth.set_radio_frequency(telemetry_state.frequency);
309 altos_bluetooth.set_telemetry_rate(telemetry_state.telemetry_rate);
310 } catch (TimeoutException e) {
311 // If this timed out, then we really want to retry it, but
312 // probably safer to just retry the connection from scratch.
313 handler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
317 if (D) Log.d(TAG, "connected bluetooth configured");
318 telemetry_state.connect = TelemetryState.CONNECT_CONNECTED;
319 telemetry_state.address = address;
321 telemetry_reader = new TelemetryReader(altos_bluetooth, handler, telemetry_state.state);
322 telemetry_reader.start();
324 if (D) Log.d(TAG, "connected TelemetryReader started");
326 telemetry_logger = new TelemetryLogger(this, altos_bluetooth);
328 if (D) Log.d(TAG, "Notify UI of connection");
335 public void onCreate() {
336 // Get local Bluetooth adapter
337 bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
339 // If the adapter is null, then Bluetooth is not supported
340 if (bluetooth_adapter == null) {
341 Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
344 // Initialise preferences
345 AltosDroidPreferences.init(this);
347 telemetry_state = new TelemetryState();
349 // Create a reference to the NotificationManager so that we can update our notifcation text later
350 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
352 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
353 telemetry_state.address = null;
355 AltosSavedState saved_state = AltosPreferences.state(0);
357 if (saved_state != null) {
358 if (D) Log.d(TAG, String.format("recovered old state flight %d\n", saved_state.state.flight));
359 telemetry_state.state = saved_state.state;
362 // Listen for GPS and Network position updates
363 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
365 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
367 DeviceAddress address = AltosDroidPreferences.active_device();
369 start_altos_bluetooth(address);
373 public int onStartCommand(Intent intent, int flags, int startId) {
374 Log.i("TelemetryService", "Received start id " + startId + ": " + intent);
376 CharSequence text = getText(R.string.telemetry_service_started);
378 // Create notification to be displayed while the service runs
379 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
381 // The PendingIntent to launch our activity if the user selects this notification
382 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
383 new Intent(this, AltosDroid.class), 0);
385 // Set the info for the views that show in the notification panel.
386 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
388 // Set the notification to be in the "Ongoing" section.
389 notification.flags |= Notification.FLAG_ONGOING_EVENT;
391 // Move us into the foreground.
392 startForeground(NOTIFICATION, notification);
394 // We want this service to continue running until it is explicitly
395 // stopped, so return sticky.
400 public void onDestroy() {
402 // Stop listening for location updates
403 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
405 // Stop the bluetooth Comms threads
406 stop_altos_bluetooth(true);
408 // Demote us from the foreground, and cancel the persistent notification.
409 stopForeground(true);
411 // Tell the user we stopped.
412 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
416 public IBinder onBind(Intent intent) {
417 return messenger.getBinder();
421 public void onLocationChanged(Location location) {
422 telemetry_state.location = location;
423 if (D) Log.d(TAG, "location changed");
427 public void onStatusChanged(String provider, int status, Bundle extras) {
430 public void onProviderEnabled(String provider) {
433 public void onProviderDisabled(String provider) {