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();
101 /* Messages from application */
102 case MSG_REGISTER_CLIENT:
103 s.add_client(msg.replyTo);
105 case MSG_UNREGISTER_CLIENT:
106 s.remove_client(msg.replyTo);
109 if (D) Log.d(TAG, "Connect command received");
110 DeviceAddress address = (DeviceAddress) msg.obj;
111 AltosDroidPreferences.set_active_device(address);
112 s.start_altos_bluetooth(address);
115 if (D) Log.d(TAG, "Disconnect command received");
117 s.stop_altos_bluetooth(true);
119 case MSG_SETFREQUENCY:
120 if (D) Log.d(TAG, "MSG_SETFREQUENCY");
121 s.telemetry_state.frequency = (Double) msg.obj;
122 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
124 s.altos_bluetooth.set_radio_frequency(s.telemetry_state.frequency);
125 s.altos_bluetooth.save_frequency();
126 } catch (InterruptedException e) {
127 } catch (TimeoutException e) {
133 if (D) Log.d(TAG, "MSG_SETBAUD");
134 s.telemetry_state.telemetry_rate = (Integer) msg.obj;
135 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
136 s.altos_bluetooth.set_telemetry_rate(s.telemetry_state.telemetry_rate);
137 s.altos_bluetooth.save_telemetry_rate();
143 *Messages from AltosBluetooth
146 if (D) Log.d(TAG, "Connected to device");
149 } catch (InterruptedException ie) {
152 case MSG_CONNECT_FAILED:
153 if (s.address != null) {
154 if (D) Log.d(TAG, "Connection failed... retrying");
155 s.start_altos_bluetooth(s.address);
157 s.stop_altos_bluetooth(true);
160 case MSG_DISCONNECTED:
161 Log.d(TAG, "MSG_DISCONNECTED");
162 if (s.address != null) {
163 if (D) Log.d(TAG, "Connection lost... retrying");
164 s.start_altos_bluetooth(s.address);
166 s.stop_altos_bluetooth(true);
171 * Messages from TelemetryReader
174 s.telemetry_state.state = (AltosState) msg.obj;
175 if (s.telemetry_state.state != null) {
176 if (D) Log.d(TAG, "Save state");
177 AltosPreferences.set_state(0, s.telemetry_state.state, null);
179 if (D) Log.d(TAG, "MSG_TELEMETRY");
183 // forward crc error messages
184 s.telemetry_state.crc_errors = (Integer) msg.obj;
185 if (D) Log.d(TAG, "MSG_CRC_ERROR");
189 super.handleMessage(msg);
194 /* Construct the message to deliver to clients
196 private Message message() {
197 if (telemetry_state == null)
198 Log.d(TAG, "telemetry_state null!");
199 if (telemetry_state.state == null)
200 Log.d(TAG, "telemetry_state.state null!");
201 return Message.obtain(null, AltosDroid.MSG_STATE, telemetry_state);
204 /* A new friend has connected
206 private void add_client(Messenger client) {
209 if (D) Log.d(TAG, "Client bound to service");
211 /* On connect, send the current state to the new client
213 send_to_client(client, message());
215 /* If we've got an address from a previous session, then
216 * go ahead and try to reconnect to the device
218 if (address != null && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
219 if (D) Log.d(TAG, "Reconnecting now...");
220 start_altos_bluetooth(address);
224 /* A client has disconnected, clean up
226 private void remove_client(Messenger client) {
227 clients.remove(client);
228 if (D) Log.d(TAG, "Client unbound from service");
230 /* When the list of clients is empty, stop the service if
231 * we have no current telemetry source
234 if (clients.isEmpty() && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
235 if (!D) Log.d(TAG, "No clients, no connection. Stopping\n");
240 private void send_to_client(Messenger client, Message m) {
242 if (D) Log.d(TAG, String.format("Send message to client %s", client.toString()));
244 } catch (RemoteException e) {
245 if (D) Log.e(TAG, String.format("Client %s disappeared", client.toString()));
246 remove_client(client);
250 private void send_to_clients() {
251 Message m = message();
252 if (D) Log.d(TAG, String.format("Send message to %d clients", clients.size()));
253 for (Messenger client : clients)
254 send_to_client(client, m);
257 private void stop_altos_bluetooth(boolean notify) {
258 if (D) Log.d(TAG, "stop_altos_bluetooth(): begin");
259 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
260 telemetry_state.address = null;
262 if (altos_bluetooth != null)
263 altos_bluetooth.closing();
265 if (telemetry_reader != null) {
266 if (D) Log.d(TAG, "stop_altos_bluetooth(): stopping TelemetryReader");
267 telemetry_reader.interrupt();
269 telemetry_reader.join();
270 } catch (InterruptedException e) {
272 telemetry_reader = null;
274 if (telemetry_logger != null) {
275 if (D) Log.d(TAG, "stop_altos_bluetooth(): stopping TelemetryLogger");
276 telemetry_logger.stop();
277 telemetry_logger = null;
279 if (altos_bluetooth != null) {
280 if (D) Log.d(TAG, "stop_altos_bluetooth(): stopping AltosBluetooth");
281 altos_bluetooth.close();
282 altos_bluetooth = null;
284 telemetry_state.config = null;
286 if (D) Log.d(TAG, "stop_altos_bluetooth(): send message to clients");
288 if (clients.isEmpty()) {
289 if (D) Log.d(TAG, "stop_altos_bluetooth(): no clients, terminating");
295 private void start_altos_bluetooth(DeviceAddress address) {
296 // Get the BLuetoothDevice object
297 BluetoothDevice device = bluetooth_adapter.getRemoteDevice(address.address);
299 stop_altos_bluetooth(false);
300 this.address = address;
301 if (D) Log.d(TAG, String.format("start_altos_bluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress()));
302 altos_bluetooth = new AltosBluetooth(device, handler);
303 telemetry_state.connect = TelemetryState.CONNECT_CONNECTING;
304 telemetry_state.address = address;
308 private void connected() throws InterruptedException {
309 if (D) Log.d(TAG, "connected top");
311 if (altos_bluetooth == null)
312 throw new InterruptedException("no bluetooth");
313 telemetry_state.config = altos_bluetooth.config_data();
314 altos_bluetooth.set_radio_frequency(telemetry_state.frequency);
315 altos_bluetooth.set_telemetry_rate(telemetry_state.telemetry_rate);
316 } catch (TimeoutException e) {
317 // If this timed out, then we really want to retry it, but
318 // probably safer to just retry the connection from scratch.
319 handler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
323 if (D) Log.d(TAG, "connected bluetooth configured");
324 telemetry_state.connect = TelemetryState.CONNECT_CONNECTED;
325 telemetry_state.address = address;
327 telemetry_reader = new TelemetryReader(altos_bluetooth, handler, telemetry_state.state);
328 telemetry_reader.start();
330 if (D) Log.d(TAG, "connected TelemetryReader started");
332 telemetry_logger = new TelemetryLogger(this, altos_bluetooth);
334 if (D) Log.d(TAG, "Notify UI of connection");
341 public void onCreate() {
342 // Get local Bluetooth adapter
343 bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
345 // If the adapter is null, then Bluetooth is not supported
346 if (bluetooth_adapter == null) {
347 Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
350 // Initialise preferences
351 AltosDroidPreferences.init(this);
353 telemetry_state = new TelemetryState();
355 // Create a reference to the NotificationManager so that we can update our notifcation text later
356 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
358 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
359 telemetry_state.address = null;
361 AltosSavedState saved_state = AltosPreferences.state(0);
363 if (saved_state != null) {
364 if (D) Log.d(TAG, String.format("recovered old state flight %d\n", saved_state.state.flight));
365 telemetry_state.state = saved_state.state;
368 // Listen for GPS and Network position updates
369 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
371 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
373 DeviceAddress address = AltosDroidPreferences.active_device();
375 start_altos_bluetooth(address);
379 public int onStartCommand(Intent intent, int flags, int startId) {
380 Log.i("TelemetryService", "Received start id " + startId + ": " + intent);
382 CharSequence text = getText(R.string.telemetry_service_started);
384 // Create notification to be displayed while the service runs
385 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
387 // The PendingIntent to launch our activity if the user selects this notification
388 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
389 new Intent(this, AltosDroid.class), 0);
391 // Set the info for the views that show in the notification panel.
392 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
394 // Set the notification to be in the "Ongoing" section.
395 notification.flags |= Notification.FLAG_ONGOING_EVENT;
397 // Move us into the foreground.
398 startForeground(NOTIFICATION, notification);
400 // We want this service to continue running until it is explicitly
401 // stopped, so return sticky.
406 public void onDestroy() {
408 // Stop listening for location updates
409 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
411 // Stop the bluetooth Comms threads
412 stop_altos_bluetooth(true);
414 // Demote us from the foreground, and cancel the persistent notification.
415 stopForeground(true);
417 // Tell the user we stopped.
418 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
422 public IBinder onBind(Intent intent) {
423 return messenger.getBinder();
427 public void onLocationChanged(Location location) {
428 telemetry_state.location = location;
429 if (D) Log.d(TAG, "location changed");
433 public void onStatusChanged(String provider, int status, Bundle extras) {
436 public void onProviderEnabled(String provider) {
439 public void onProviderDisabled(String provider) {