altosui/telegps: Change from variable-units snuck into master
[fw/altos] / altosdroid / src / org / altusmetrum / AltosDroid / TelemetryService.java
1 /*
2  * Copyright © 2012 Mike Beattie <mike@ethernal.org>
3  *
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.
7  *
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.
12  *
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.
16  */
17
18 package org.altusmetrum.AltosDroid;
19
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;
25
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;
47
48 import org.altusmetrum.altoslib_6.*;
49
50
51 public class TelemetryService extends Service implements LocationListener {
52
53         private static final String TAG = "TelemetryService";
54         private static final boolean D = true;
55
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;
67
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;
72
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.
76
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;
82
83         // Local Bluetooth adapter
84         private BluetoothAdapter bluetooth_adapter = null;
85
86         // Last data seen; send to UI when it starts
87         private TelemetryState  telemetry_state;
88
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); }
93
94                 @Override
95                 public void handleMessage(Message msg) {
96                         TelemetryService s = service.get();
97                         if (s == null)
98                                 return;
99                         switch (msg.what) {
100
101                                 /* Messages from application */
102                         case MSG_REGISTER_CLIENT:
103                                 s.add_client(msg.replyTo);
104                                 break;
105                         case MSG_UNREGISTER_CLIENT:
106                                 s.remove_client(msg.replyTo);
107                                 break;
108                         case MSG_CONNECT:
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);
113                                 break;
114                         case MSG_DISCONNECT:
115                                 if (D) Log.d(TAG, "Disconnect command received");
116                                 s.address = null;
117                                 s.stop_altos_bluetooth(true);
118                                 break;
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) {
123                                         try {
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) {
128                                         }
129                                 }
130                                 s.send_to_clients();
131                                 break;
132                         case MSG_SETBAUD:
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();
138                                 }
139                                 s.send_to_clients();
140                                 break;
141
142                                 /*
143                                  *Messages from AltosBluetooth
144                                  */
145                         case MSG_CONNECTED:
146                                 if (D) Log.d(TAG, "Connected to device");
147                                 try {
148                                         s.connected();
149                                 } catch (InterruptedException ie) {
150                                 }
151                                 break;
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);
156                                 } else {
157                                         s.stop_altos_bluetooth(true);
158                                 }
159                                 break;
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);
165                                 } else {
166                                         s.stop_altos_bluetooth(true);
167                                 }
168                                 break;
169
170                                 /*
171                                  * Messages from TelemetryReader
172                                  */
173                         case MSG_TELEMETRY:
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);
178                                 }
179                                 if (D) Log.d(TAG, "MSG_TELEMETRY");
180                                 s.send_to_clients();
181                                 break;
182                         case MSG_CRC_ERROR:
183                                 // forward crc error messages
184                                 s.telemetry_state.crc_errors = (Integer) msg.obj;
185                                 if (D) Log.d(TAG, "MSG_CRC_ERROR");
186                                 s.send_to_clients();
187                                 break;
188                         default:
189                                 super.handleMessage(msg);
190                         }
191                 }
192         }
193
194         /* Construct the message to deliver to clients
195          */
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);
202         }
203
204         /* A new friend has connected
205          */
206         private void add_client(Messenger client) {
207
208                 clients.add(client);
209                 if (D) Log.d(TAG, "Client bound to service");
210
211                 /* On connect, send the current state to the new client
212                  */
213                 send_to_client(client, message());
214
215                 /* If we've got an address from a previous session, then
216                  * go ahead and try to reconnect to the device
217                  */
218                 if (address != null && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
219                         if (D) Log.d(TAG, "Reconnecting now...");
220                         start_altos_bluetooth(address);
221                 }
222         }
223
224         /* A client has disconnected, clean up
225          */
226         private void remove_client(Messenger client) {
227                 clients.remove(client);
228                 if (D) Log.d(TAG, "Client unbound from service");
229
230                 /* When the list of clients is empty, stop the service if
231                  * we have no current telemetry source
232                  */
233
234                  if (clients.isEmpty() && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
235                          if (!D) Log.d(TAG, "No clients, no connection. Stopping\n");
236                          stopSelf();
237                  }
238         }
239
240         private void send_to_client(Messenger client, Message m) {
241                 try {
242                         if (D) Log.d(TAG, String.format("Send message to client %s", client.toString()));
243                         client.send(m);
244                 } catch (RemoteException e) {
245                         if (D) Log.e(TAG, String.format("Client %s disappeared", client.toString()));
246                         remove_client(client);
247                 }
248         }
249
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);
255         }
256
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;
261
262                 if (altos_bluetooth != null)
263                         altos_bluetooth.closing();
264
265                 if (telemetry_reader != null) {
266                         if (D) Log.d(TAG, "stop_altos_bluetooth(): stopping TelemetryReader");
267                         telemetry_reader.interrupt();
268                         try {
269                                 telemetry_reader.join();
270                         } catch (InterruptedException e) {
271                         }
272                         telemetry_reader = null;
273                 }
274                 if (telemetry_logger != null) {
275                         if (D) Log.d(TAG, "stop_altos_bluetooth(): stopping TelemetryLogger");
276                         telemetry_logger.stop();
277                         telemetry_logger = null;
278                 }
279                 if (altos_bluetooth != null) {
280                         if (D) Log.d(TAG, "stop_altos_bluetooth(): stopping AltosBluetooth");
281                         altos_bluetooth.close();
282                         altos_bluetooth = null;
283                 }
284                 telemetry_state.config = null;
285                 if (notify) {
286                         if (D) Log.d(TAG, "stop_altos_bluetooth(): send message to clients");
287                         send_to_clients();
288                         if (clients.isEmpty()) {
289                                 if (D) Log.d(TAG, "stop_altos_bluetooth(): no clients, terminating");
290                                 stopSelf();
291                         }
292                 }
293         }
294
295         private void start_altos_bluetooth(DeviceAddress address) {
296                 // Get the BLuetoothDevice object
297                 BluetoothDevice device = bluetooth_adapter.getRemoteDevice(address.address);
298
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;
305                 send_to_clients();
306         }
307
308         private void connected() throws InterruptedException {
309                 if (D) Log.d(TAG, "connected top");
310                 try {
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();
320                         return;
321                 }
322
323                 if (D) Log.d(TAG, "connected bluetooth configured");
324                 telemetry_state.connect = TelemetryState.CONNECT_CONNECTED;
325                 telemetry_state.address = address;
326
327                 telemetry_reader = new TelemetryReader(altos_bluetooth, handler, telemetry_state.state);
328                 telemetry_reader.start();
329
330                 if (D) Log.d(TAG, "connected TelemetryReader started");
331
332                 telemetry_logger = new TelemetryLogger(this, altos_bluetooth);
333
334                 if (D) Log.d(TAG, "Notify UI of connection");
335
336                 send_to_clients();
337         }
338
339
340         @Override
341         public void onCreate() {
342                 // Get local Bluetooth adapter
343                 bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
344
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();
348                 }
349
350                 // Initialise preferences
351                 AltosDroidPreferences.init(this);
352
353                 telemetry_state = new TelemetryState();
354
355                 // Create a reference to the NotificationManager so that we can update our notifcation text later
356                 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
357
358                 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
359                 telemetry_state.address = null;
360
361                 AltosSavedState saved_state = AltosPreferences.state(0);
362
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;
366                 }
367
368                 // Listen for GPS and Network position updates
369                 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
370
371                 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
372
373                 DeviceAddress address = AltosDroidPreferences.active_device();
374                 if (address != null)
375                         start_altos_bluetooth(address);
376         }
377
378         @Override
379         public int onStartCommand(Intent intent, int flags, int startId) {
380                 Log.i("TelemetryService", "Received start id " + startId + ": " + intent);
381
382                 CharSequence text = getText(R.string.telemetry_service_started);
383
384                 // Create notification to be displayed while the service runs
385                 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
386
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);
390
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);
393
394                 // Set the notification to be in the "Ongoing" section.
395                 notification.flags |= Notification.FLAG_ONGOING_EVENT;
396
397                 // Move us into the foreground.
398                 startForeground(NOTIFICATION, notification);
399
400                 // We want this service to continue running until it is explicitly
401                 // stopped, so return sticky.
402                 return START_STICKY;
403         }
404
405         @Override
406         public void onDestroy() {
407
408                 // Stop listening for location updates
409                 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
410
411                 // Stop the bluetooth Comms threads
412                 stop_altos_bluetooth(true);
413
414                 // Demote us from the foreground, and cancel the persistent notification.
415                 stopForeground(true);
416
417                 // Tell the user we stopped.
418                 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
419         }
420
421         @Override
422         public IBinder onBind(Intent intent) {
423                 return messenger.getBinder();
424         }
425
426
427         public void onLocationChanged(Location location) {
428                 telemetry_state.location = location;
429                 if (D) Log.d(TAG, "location changed");
430                 send_to_clients();
431         }
432
433         public void onStatusChanged(String provider, int status, Bundle extras) {
434         }
435
436         public void onProviderEnabled(String provider) {
437         }
438
439         public void onProviderDisabled(String provider) {
440         }
441
442 }