ed7b75a1ef1ab470ad4ecc39ed5cdeb25aa635f9
[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.hardware.usb.*;
33 import android.content.Intent;
34 import android.content.Context;
35 import android.os.Bundle;
36 import android.os.IBinder;
37 import android.os.Handler;
38 import android.os.Message;
39 import android.os.Messenger;
40 import android.os.RemoteException;
41 import android.os.Looper;
42 import android.util.Log;
43 import android.widget.Toast;
44 import android.location.Location;
45 import android.location.LocationManager;
46 import android.location.LocationListener;
47 import android.location.Criteria;
48
49 import org.altusmetrum.altoslib_7.*;
50
51
52 public class TelemetryService extends Service implements LocationListener {
53
54         private static final String TAG = "TelemetryService";
55         private static final boolean D = true;
56
57         static final int MSG_REGISTER_CLIENT   = 1;
58         static final int MSG_UNREGISTER_CLIENT = 2;
59         static final int MSG_CONNECT           = 3;
60         static final int MSG_OPEN_USB          = 4;
61         static final int MSG_CONNECTED         = 5;
62         static final int MSG_CONNECT_FAILED    = 6;
63         static final int MSG_DISCONNECTED      = 7;
64         static final int MSG_TELEMETRY         = 8;
65         static final int MSG_SETFREQUENCY      = 9;
66         static final int MSG_CRC_ERROR         = 10;
67         static final int MSG_SETBAUD           = 11;
68         static final int MSG_DISCONNECT        = 12;
69
70         // Unique Identification Number for the Notification.
71         // We use it on Notification start, and to cancel it.
72         private int NOTIFICATION = R.string.telemetry_service_label;
73         //private NotificationManager mNM;
74
75         ArrayList<Messenger> clients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
76         final Handler   handler   = new IncomingHandler(this);
77         final Messenger messenger = new Messenger(handler); // Target we publish for clients to send messages to IncomingHandler.
78
79         // Name of the connected device
80         DeviceAddress address;
81         private AltosDroidLink  altos_link  = null;
82         private TelemetryReader telemetry_reader = null;
83         private TelemetryLogger telemetry_logger = null;
84
85         // Local Bluetooth adapter
86         private BluetoothAdapter bluetooth_adapter = null;
87
88         // Last data seen; send to UI when it starts
89         private TelemetryState  telemetry_state;
90
91         // Handler of incoming messages from clients.
92         static class IncomingHandler extends Handler {
93                 private final WeakReference<TelemetryService> service;
94                 IncomingHandler(TelemetryService s) { service = new WeakReference<TelemetryService>(s); }
95
96                 @Override
97                 public void handleMessage(Message msg) {
98                         TelemetryService s = service.get();
99                         AltosDroidLink bt = null;
100                         if (s == null)
101                                 return;
102                         switch (msg.what) {
103
104                                 /* Messages from application */
105                         case MSG_REGISTER_CLIENT:
106                                 s.add_client(msg.replyTo);
107                                 break;
108                         case MSG_UNREGISTER_CLIENT:
109                                 s.remove_client(msg.replyTo);
110                                 break;
111                         case MSG_CONNECT:
112                                 if (D) Log.d(TAG, "Connect command received");
113                                 DeviceAddress address = (DeviceAddress) msg.obj;
114                                 AltosDroidPreferences.set_active_device(address);
115                                 s.start_altos_bluetooth(address, false);
116                                 break;
117                         case MSG_OPEN_USB:
118                                 if (D) Log.d(TAG, "Open USB command received");
119                                 UsbDevice device = (UsbDevice) msg.obj;
120                                 s.start_usb(device);
121                                 break;
122                         case MSG_DISCONNECT:
123                                 if (D) Log.d(TAG, "Disconnect command received");
124                                 s.address = null;
125                                 s.disconnect(true);
126                                 break;
127                         case MSG_SETFREQUENCY:
128                                 if (D) Log.d(TAG, "MSG_SETFREQUENCY");
129                                 s.telemetry_state.frequency = (Double) msg.obj;
130                                 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
131                                         try {
132                                                 s.altos_link.set_radio_frequency(s.telemetry_state.frequency);
133                                                 s.altos_link.save_frequency();
134                                         } catch (InterruptedException e) {
135                                         } catch (TimeoutException e) {
136                                         }
137                                 }
138                                 s.send_to_clients();
139                                 break;
140                         case MSG_SETBAUD:
141                                 if (D) Log.d(TAG, "MSG_SETBAUD");
142                                 s.telemetry_state.telemetry_rate = (Integer) msg.obj;
143                                 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
144                                         s.altos_link.set_telemetry_rate(s.telemetry_state.telemetry_rate);
145                                         s.altos_link.save_telemetry_rate();
146                                 }
147                                 s.send_to_clients();
148                                 break;
149
150                                 /*
151                                  *Messages from AltosBluetooth
152                                  */
153                         case MSG_CONNECTED:
154                                 Log.d(TAG, "MSG_CONNECTED");
155                                 bt = (AltosDroidLink) msg.obj;
156
157                                 if (bt != s.altos_link) {
158                                         if (D) Log.d(TAG, "Stale message");
159                                         break;
160                                 }
161                                 if (D) Log.d(TAG, "Connected to device");
162                                 try {
163                                         s.connected();
164                                 } catch (InterruptedException ie) {
165                                 }
166                                 break;
167                         case MSG_CONNECT_FAILED:
168                                 Log.d(TAG, "MSG_CONNECT_FAILED");
169                                 bt = (AltosDroidLink) msg.obj;
170
171                                 if (bt != s.altos_link) {
172                                         if (D) Log.d(TAG, "Stale message");
173                                         break;
174                                 }
175                                 if (s.address != null) {
176                                         if (D) Log.d(TAG, "Connection failed... retrying");
177                                         s.start_altos_bluetooth(s.address, true);
178                                 } else {
179                                         s.disconnect(true);
180                                 }
181                                 break;
182                         case MSG_DISCONNECTED:
183
184                                 /* This can be sent by either AltosDroidLink or TelemetryReader */
185                                 Log.d(TAG, "MSG_DISCONNECTED");
186                                 bt = (AltosDroidLink) msg.obj;
187
188                                 if (bt != s.altos_link) {
189                                         if (D) Log.d(TAG, "Stale message");
190                                         break;
191                                 }
192                                 if (s.address != null) {
193                                         if (D) Log.d(TAG, "Connection lost... retrying");
194                                         s.start_altos_bluetooth(s.address, true);
195                                 } else {
196                                         s.disconnect(true);
197                                 }
198                                 break;
199
200                                 /*
201                                  * Messages from TelemetryReader
202                                  */
203                         case MSG_TELEMETRY:
204                                 s.telemetry_state.state = (AltosState) msg.obj;
205                                 if (s.telemetry_state.state != null) {
206                                         if (D) Log.d(TAG, "Save state");
207                                         AltosPreferences.set_state(0, s.telemetry_state.state, null);
208                                 }
209                                 if (D) Log.d(TAG, "MSG_TELEMETRY");
210                                 s.send_to_clients();
211                                 break;
212                         case MSG_CRC_ERROR:
213                                 // forward crc error messages
214                                 s.telemetry_state.crc_errors = (Integer) msg.obj;
215                                 if (D) Log.d(TAG, "MSG_CRC_ERROR");
216                                 s.send_to_clients();
217                                 break;
218                         default:
219                                 super.handleMessage(msg);
220                         }
221                 }
222         }
223
224         /* Construct the message to deliver to clients
225          */
226         private Message message() {
227                 if (telemetry_state == null)
228                         Log.d(TAG, "telemetry_state null!");
229                 if (telemetry_state.state == null)
230                         Log.d(TAG, "telemetry_state.state null!");
231                 return Message.obtain(null, AltosDroid.MSG_STATE, telemetry_state);
232         }
233
234         /* A new friend has connected
235          */
236         private void add_client(Messenger client) {
237
238                 clients.add(client);
239                 if (D) Log.d(TAG, "Client bound to service");
240
241                 /* On connect, send the current state to the new client
242                  */
243                 send_to_client(client, message());
244
245                 /* If we've got an address from a previous session, then
246                  * go ahead and try to reconnect to the device
247                  */
248                 if (address != null && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
249                         if (D) Log.d(TAG, "Reconnecting now...");
250                         start_altos_bluetooth(address, false);
251                 }
252         }
253
254         /* A client has disconnected, clean up
255          */
256         private void remove_client(Messenger client) {
257                 clients.remove(client);
258                 if (D) Log.d(TAG, "Client unbound from service");
259
260                 /* When the list of clients is empty, stop the service if
261                  * we have no current telemetry source
262                  */
263
264                  if (clients.isEmpty() && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
265                          if (!D) Log.d(TAG, "No clients, no connection. Stopping\n");
266                          stopSelf();
267                  }
268         }
269
270         private void send_to_client(Messenger client, Message m) {
271                 try {
272                         if (D) Log.d(TAG, String.format("Send message to client %s", client.toString()));
273                         client.send(m);
274                 } catch (RemoteException e) {
275                         if (D) Log.e(TAG, String.format("Client %s disappeared", client.toString()));
276                         remove_client(client);
277                 }
278         }
279
280         private void send_to_clients() {
281                 Message m = message();
282                 if (D) Log.d(TAG, String.format("Send message to %d clients", clients.size()));
283                 for (Messenger client : clients)
284                         send_to_client(client, m);
285         }
286
287         private void disconnect(boolean notify) {
288                 if (D) Log.d(TAG, "disconnect(): begin");
289
290                 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
291                 telemetry_state.address = null;
292
293                 if (altos_link != null)
294                         altos_link.closing();
295
296                 if (telemetry_reader != null) {
297                         if (D) Log.d(TAG, "disconnect(): stopping TelemetryReader");
298                         telemetry_reader.interrupt();
299                         try {
300                                 telemetry_reader.join();
301                         } catch (InterruptedException e) {
302                         }
303                         telemetry_reader = null;
304                 }
305                 if (telemetry_logger != null) {
306                         if (D) Log.d(TAG, "disconnect(): stopping TelemetryLogger");
307                         telemetry_logger.stop();
308                         telemetry_logger = null;
309                 }
310                 if (altos_link != null) {
311                         if (D) Log.d(TAG, "disconnect(): stopping AltosDroidLink");
312                         altos_link.close();
313                         altos_link = null;
314                 }
315                 telemetry_state.config = null;
316                 if (notify) {
317                         if (D) Log.d(TAG, "disconnect(): send message to clients");
318                         send_to_clients();
319                         if (clients.isEmpty()) {
320                                 if (D) Log.d(TAG, "disconnect(): no clients, terminating");
321                                 stopSelf();
322                         }
323                 }
324         }
325
326         private void start_usb(UsbDevice device) {
327                 AltosUsb        d = new AltosUsb(this, device, handler);
328
329                 if (d != null) {
330                         disconnect(false);
331                         altos_link = d;
332                         try {
333                                 connected();
334                         } catch (InterruptedException ie) {
335                         }
336                 }
337         }
338
339         private void start_altos_bluetooth(DeviceAddress address, boolean pause) {
340                 // Get the BLuetoothDevice object
341                 BluetoothDevice device = bluetooth_adapter.getRemoteDevice(address.address);
342
343                 disconnect(false);
344                 this.address = address;
345                 if (D) Log.d(TAG, String.format("start_altos_bluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress()));
346                 altos_link = new AltosBluetooth(device, handler);
347                 telemetry_state.connect = TelemetryState.CONNECT_CONNECTING;
348                 telemetry_state.address = address;
349                 send_to_clients();
350         }
351
352         private void connected() throws InterruptedException {
353                 if (D) Log.d(TAG, "connected top");
354                 try {
355                         if (altos_link == null)
356                                 throw new InterruptedException("no bluetooth");
357                         telemetry_state.config = altos_link.config_data();
358                         altos_link.set_radio_frequency(telemetry_state.frequency);
359                         altos_link.set_telemetry_rate(telemetry_state.telemetry_rate);
360                 } catch (TimeoutException e) {
361                         // If this timed out, then we really want to retry it, but
362                         // probably safer to just retry the connection from scratch.
363                         if (D) Log.d(TAG, "connected timeout");
364                         if (address != null) {
365                                 if (D) Log.d(TAG, "connected timeout, retrying");
366                                 start_altos_bluetooth(address, true);
367                         } else {
368                                 handler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
369                                 disconnect(true);
370                         }
371                         return;
372                 }
373
374                 if (D) Log.d(TAG, "connected bluetooth configured");
375                 telemetry_state.connect = TelemetryState.CONNECT_CONNECTED;
376                 telemetry_state.address = address;
377
378                 telemetry_reader = new TelemetryReader(altos_link, handler, telemetry_state.state);
379                 telemetry_reader.start();
380
381                 if (D) Log.d(TAG, "connected TelemetryReader started");
382
383                 telemetry_logger = new TelemetryLogger(this, altos_link);
384
385                 if (D) Log.d(TAG, "Notify UI of connection");
386
387                 send_to_clients();
388         }
389
390
391         @Override
392         public void onCreate() {
393                 // Get local Bluetooth adapter
394                 bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
395
396                 // If the adapter is null, then Bluetooth is not supported
397                 if (bluetooth_adapter == null) {
398                         Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
399                 }
400
401                 // Initialise preferences
402                 AltosDroidPreferences.init(this);
403
404                 telemetry_state = new TelemetryState();
405
406                 // Create a reference to the NotificationManager so that we can update our notifcation text later
407                 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
408
409                 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
410                 telemetry_state.address = null;
411
412                 AltosSavedState saved_state = AltosPreferences.state(0);
413
414                 if (saved_state != null) {
415                         if (D) Log.d(TAG, String.format("recovered old state flight %d\n", saved_state.state.flight));
416                         telemetry_state.state = saved_state.state;
417                 }
418
419                 // Listen for GPS and Network position updates
420                 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
421
422                 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
423         }
424
425         @Override
426         public int onStartCommand(Intent intent, int flags, int startId) {
427                 Log.i("TelemetryService", "Received start id " + startId + ": " + intent);
428
429                 CharSequence text = getText(R.string.telemetry_service_started);
430
431                 // Create notification to be displayed while the service runs
432                 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
433
434                 // The PendingIntent to launch our activity if the user selects this notification
435                 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
436                                 new Intent(this, AltosDroid.class), 0);
437
438                 // Set the info for the views that show in the notification panel.
439                 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
440
441                 // Set the notification to be in the "Ongoing" section.
442                 notification.flags |= Notification.FLAG_ONGOING_EVENT;
443
444                 // Move us into the foreground.
445                 startForeground(NOTIFICATION, notification);
446
447                 if (intent != null) {
448                         String  action = intent.getAction();
449
450                         if (action.equals(AltosDroid.ACTION_BLUETOOTH)) {
451                                 DeviceAddress address = AltosDroidPreferences.active_device();
452                                 if (address != null && !address.address.startsWith("USB"))
453                                         start_altos_bluetooth(address, false);
454                         }
455                 }
456
457                 // We want this service to continue running until it is explicitly
458                 // stopped, so return sticky.
459                 return START_STICKY;
460         }
461
462         @Override
463         public void onDestroy() {
464
465                 // Stop listening for location updates
466                 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
467
468                 // Stop the bluetooth Comms threads
469                 disconnect(true);
470
471                 // Demote us from the foreground, and cancel the persistent notification.
472                 stopForeground(true);
473
474                 // Tell the user we stopped.
475                 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
476         }
477
478         @Override
479         public IBinder onBind(Intent intent) {
480                 return messenger.getBinder();
481         }
482
483
484         public void onLocationChanged(Location location) {
485                 telemetry_state.location = location;
486                 if (D) Log.d(TAG, "location changed");
487                 send_to_clients();
488         }
489
490         public void onStatusChanged(String provider, int status, Bundle extras) {
491         }
492
493         public void onProviderEnabled(String provider) {
494         }
495
496         public void onProviderDisabled(String provider) {
497         }
498
499 }