65eabf1166a394f5fdeb4a584dddbd765594b385
[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                         AltosBluetooth bt = null;
98                         if (s == null)
99                                 return;
100                         switch (msg.what) {
101
102                                 /* Messages from application */
103                         case MSG_REGISTER_CLIENT:
104                                 s.add_client(msg.replyTo);
105                                 break;
106                         case MSG_UNREGISTER_CLIENT:
107                                 s.remove_client(msg.replyTo);
108                                 break;
109                         case MSG_CONNECT:
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);
114                                 break;
115                         case MSG_DISCONNECT:
116                                 if (D) Log.d(TAG, "Disconnect command received");
117                                 s.address = null;
118                                 s.stop_altos_bluetooth(true);
119                                 break;
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) {
124                                         try {
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) {
129                                         }
130                                 }
131                                 s.send_to_clients();
132                                 break;
133                         case MSG_SETBAUD:
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();
139                                 }
140                                 s.send_to_clients();
141                                 break;
142
143                                 /*
144                                  *Messages from AltosBluetooth
145                                  */
146                         case MSG_CONNECTED:
147                                 Log.d(TAG, "MSG_CONNECTED");
148                                 bt = (AltosBluetooth) msg.obj;
149
150                                 if (bt != s.altos_bluetooth) {
151                                         if (D) Log.d(TAG, "Stale message");
152                                         break;
153                                 }
154                                 if (D) Log.d(TAG, "Connected to device");
155                                 try {
156                                         s.connected();
157                                 } catch (InterruptedException ie) {
158                                 }
159                                 break;
160                         case MSG_CONNECT_FAILED:
161                                 Log.d(TAG, "MSG_CONNECT_FAILED");
162                                 bt = (AltosBluetooth) msg.obj;
163
164                                 if (bt != s.altos_bluetooth) {
165                                         if (D) Log.d(TAG, "Stale message");
166                                         break;
167                                 }
168                                 if (s.address != null) {
169                                         if (D) Log.d(TAG, "Connection failed... retrying");
170                                         s.start_altos_bluetooth(s.address, true);
171                                 } else {
172                                         s.stop_altos_bluetooth(true);
173                                 }
174                                 break;
175                         case MSG_DISCONNECTED:
176                                 Log.d(TAG, "MSG_DISCONNECTED");
177                                 bt = (AltosBluetooth) msg.obj;
178
179                                 if (bt != s.altos_bluetooth) {
180                                         if (D) Log.d(TAG, "Stale message");
181                                         break;
182                                 }
183                                 if (s.address != null) {
184                                         if (D) Log.d(TAG, "Connection lost... retrying");
185                                         s.start_altos_bluetooth(s.address, true);
186                                 } else {
187                                         s.stop_altos_bluetooth(true);
188                                 }
189                                 break;
190
191                                 /*
192                                  * Messages from TelemetryReader
193                                  */
194                         case MSG_TELEMETRY:
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);
199                                 }
200                                 if (D) Log.d(TAG, "MSG_TELEMETRY");
201                                 s.send_to_clients();
202                                 break;
203                         case MSG_CRC_ERROR:
204                                 // forward crc error messages
205                                 s.telemetry_state.crc_errors = (Integer) msg.obj;
206                                 if (D) Log.d(TAG, "MSG_CRC_ERROR");
207                                 s.send_to_clients();
208                                 break;
209                         default:
210                                 super.handleMessage(msg);
211                         }
212                 }
213         }
214
215         /* Construct the message to deliver to clients
216          */
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);
223         }
224
225         /* A new friend has connected
226          */
227         private void add_client(Messenger client) {
228
229                 clients.add(client);
230                 if (D) Log.d(TAG, "Client bound to service");
231
232                 /* On connect, send the current state to the new client
233                  */
234                 send_to_client(client, message());
235
236                 /* If we've got an address from a previous session, then
237                  * go ahead and try to reconnect to the device
238                  */
239                 if (address != null && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
240                         if (D) Log.d(TAG, "Reconnecting now...");
241                         start_altos_bluetooth(address, false);
242                 }
243         }
244
245         /* A client has disconnected, clean up
246          */
247         private void remove_client(Messenger client) {
248                 clients.remove(client);
249                 if (D) Log.d(TAG, "Client unbound from service");
250
251                 /* When the list of clients is empty, stop the service if
252                  * we have no current telemetry source
253                  */
254
255                  if (clients.isEmpty() && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
256                          if (!D) Log.d(TAG, "No clients, no connection. Stopping\n");
257                          stopSelf();
258                  }
259         }
260
261         private void send_to_client(Messenger client, Message m) {
262                 try {
263                         if (D) Log.d(TAG, String.format("Send message to client %s", client.toString()));
264                         client.send(m);
265                 } catch (RemoteException e) {
266                         if (D) Log.e(TAG, String.format("Client %s disappeared", client.toString()));
267                         remove_client(client);
268                 }
269         }
270
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);
276         }
277
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;
282
283                 if (altos_bluetooth != null)
284                         altos_bluetooth.closing();
285
286                 if (telemetry_reader != null) {
287                         if (D) Log.d(TAG, "stop_altos_bluetooth(): stopping TelemetryReader");
288                         telemetry_reader.interrupt();
289                         try {
290                                 telemetry_reader.join();
291                         } catch (InterruptedException e) {
292                         }
293                         telemetry_reader = null;
294                 }
295                 if (telemetry_logger != null) {
296                         if (D) Log.d(TAG, "stop_altos_bluetooth(): stopping TelemetryLogger");
297                         telemetry_logger.stop();
298                         telemetry_logger = null;
299                 }
300                 if (altos_bluetooth != null) {
301                         if (D) Log.d(TAG, "stop_altos_bluetooth(): stopping AltosBluetooth");
302                         altos_bluetooth.close();
303                         altos_bluetooth = null;
304                 }
305                 telemetry_state.config = null;
306                 if (notify) {
307                         if (D) Log.d(TAG, "stop_altos_bluetooth(): send message to clients");
308                         send_to_clients();
309                         if (clients.isEmpty()) {
310                                 if (D) Log.d(TAG, "stop_altos_bluetooth(): no clients, terminating");
311                                 stopSelf();
312                         }
313                 }
314         }
315
316         private void start_altos_bluetooth(DeviceAddress address, boolean pause) {
317                 // Get the BLuetoothDevice object
318                 BluetoothDevice device = bluetooth_adapter.getRemoteDevice(address.address);
319
320                 stop_altos_bluetooth(false);
321                 if (pause) {
322                         try {
323                                 Thread.sleep(4000);
324                         } catch (InterruptedException e) {
325                         }
326                 }
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;
332                 send_to_clients();
333         }
334
335         private void connected() throws InterruptedException {
336                 if (D) Log.d(TAG, "connected top");
337                 try {
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);
350                         } else {
351                                 handler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
352                                 stop_altos_bluetooth(true);
353                         }
354                         return;
355                 }
356
357                 if (D) Log.d(TAG, "connected bluetooth configured");
358                 telemetry_state.connect = TelemetryState.CONNECT_CONNECTED;
359                 telemetry_state.address = address;
360
361                 telemetry_reader = new TelemetryReader(altos_bluetooth, handler, telemetry_state.state);
362                 telemetry_reader.start();
363
364                 if (D) Log.d(TAG, "connected TelemetryReader started");
365
366                 telemetry_logger = new TelemetryLogger(this, altos_bluetooth);
367
368                 if (D) Log.d(TAG, "Notify UI of connection");
369
370                 send_to_clients();
371         }
372
373
374         @Override
375         public void onCreate() {
376                 // Get local Bluetooth adapter
377                 bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
378
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();
382                 }
383
384                 // Initialise preferences
385                 AltosDroidPreferences.init(this);
386
387                 telemetry_state = new TelemetryState();
388
389                 // Create a reference to the NotificationManager so that we can update our notifcation text later
390                 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
391
392                 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
393                 telemetry_state.address = null;
394
395                 AltosSavedState saved_state = AltosPreferences.state(0);
396
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;
400                 }
401
402                 // Listen for GPS and Network position updates
403                 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
404
405                 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
406
407                 DeviceAddress address = AltosDroidPreferences.active_device();
408                 if (address != null)
409                         start_altos_bluetooth(address, false);
410         }
411
412         @Override
413         public int onStartCommand(Intent intent, int flags, int startId) {
414                 Log.i("TelemetryService", "Received start id " + startId + ": " + intent);
415
416                 CharSequence text = getText(R.string.telemetry_service_started);
417
418                 // Create notification to be displayed while the service runs
419                 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
420
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);
424
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);
427
428                 // Set the notification to be in the "Ongoing" section.
429                 notification.flags |= Notification.FLAG_ONGOING_EVENT;
430
431                 // Move us into the foreground.
432                 startForeground(NOTIFICATION, notification);
433
434                 // We want this service to continue running until it is explicitly
435                 // stopped, so return sticky.
436                 return START_STICKY;
437         }
438
439         @Override
440         public void onDestroy() {
441
442                 // Stop listening for location updates
443                 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
444
445                 // Stop the bluetooth Comms threads
446                 stop_altos_bluetooth(true);
447
448                 // Demote us from the foreground, and cancel the persistent notification.
449                 stopForeground(true);
450
451                 // Tell the user we stopped.
452                 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
453         }
454
455         @Override
456         public IBinder onBind(Intent intent) {
457                 return messenger.getBinder();
458         }
459
460
461         public void onLocationChanged(Location location) {
462                 telemetry_state.location = location;
463                 if (D) Log.d(TAG, "location changed");
464                 send_to_clients();
465         }
466
467         public void onStatusChanged(String provider, int status, Bundle extras) {
468         }
469
470         public void onProviderEnabled(String provider) {
471         }
472
473         public void onProviderDisabled(String provider) {
474         }
475
476 }