altoslib/altosuilib: Update library version to 7
[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                 if (pause) {
345                         try {
346                                 Thread.sleep(4000);
347                         } catch (InterruptedException e) {
348                         }
349                 }
350                 this.address = address;
351                 if (D) Log.d(TAG, String.format("start_altos_bluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress()));
352                 altos_link = new AltosBluetooth(device, handler);
353                 telemetry_state.connect = TelemetryState.CONNECT_CONNECTING;
354                 telemetry_state.address = address;
355                 send_to_clients();
356         }
357
358         private void connected() throws InterruptedException {
359                 if (D) Log.d(TAG, "connected top");
360                 try {
361                         if (altos_link == null)
362                                 throw new InterruptedException("no bluetooth");
363                         telemetry_state.config = altos_link.config_data();
364                         altos_link.set_radio_frequency(telemetry_state.frequency);
365                         altos_link.set_telemetry_rate(telemetry_state.telemetry_rate);
366                 } catch (TimeoutException e) {
367                         // If this timed out, then we really want to retry it, but
368                         // probably safer to just retry the connection from scratch.
369                         if (D) Log.d(TAG, "connected timeout");
370                         if (address != null) {
371                                 if (D) Log.d(TAG, "connected timeout, retrying");
372                                 start_altos_bluetooth(address, true);
373                         } else {
374                                 handler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
375                                 disconnect(true);
376                         }
377                         return;
378                 }
379
380                 if (D) Log.d(TAG, "connected bluetooth configured");
381                 telemetry_state.connect = TelemetryState.CONNECT_CONNECTED;
382                 telemetry_state.address = address;
383
384                 telemetry_reader = new TelemetryReader(altos_link, handler, telemetry_state.state);
385                 telemetry_reader.start();
386
387                 if (D) Log.d(TAG, "connected TelemetryReader started");
388
389                 telemetry_logger = new TelemetryLogger(this, altos_link);
390
391                 if (D) Log.d(TAG, "Notify UI of connection");
392
393                 send_to_clients();
394         }
395
396
397         @Override
398         public void onCreate() {
399                 // Get local Bluetooth adapter
400                 bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
401
402                 // If the adapter is null, then Bluetooth is not supported
403                 if (bluetooth_adapter == null) {
404                         Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
405                 }
406
407                 // Initialise preferences
408                 AltosDroidPreferences.init(this);
409
410                 telemetry_state = new TelemetryState();
411
412                 // Create a reference to the NotificationManager so that we can update our notifcation text later
413                 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
414
415                 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
416                 telemetry_state.address = null;
417
418                 AltosSavedState saved_state = AltosPreferences.state(0);
419
420                 if (saved_state != null) {
421                         if (D) Log.d(TAG, String.format("recovered old state flight %d\n", saved_state.state.flight));
422                         telemetry_state.state = saved_state.state;
423                 }
424
425                 // Listen for GPS and Network position updates
426                 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
427
428                 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
429         }
430
431         @Override
432         public int onStartCommand(Intent intent, int flags, int startId) {
433                 Log.i("TelemetryService", "Received start id " + startId + ": " + intent);
434
435                 CharSequence text = getText(R.string.telemetry_service_started);
436
437                 // Create notification to be displayed while the service runs
438                 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
439
440                 // The PendingIntent to launch our activity if the user selects this notification
441                 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
442                                 new Intent(this, AltosDroid.class), 0);
443
444                 // Set the info for the views that show in the notification panel.
445                 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
446
447                 // Set the notification to be in the "Ongoing" section.
448                 notification.flags |= Notification.FLAG_ONGOING_EVENT;
449
450                 // Move us into the foreground.
451                 startForeground(NOTIFICATION, notification);
452
453                 String  action = intent.getAction();
454
455                 if (action.equals(AltosDroid.ACTION_BLUETOOTH)) {
456                         DeviceAddress address = AltosDroidPreferences.active_device();
457                         if (address != null && !address.address.startsWith("USB"))
458                                 start_altos_bluetooth(address, false);
459                 }
460
461                 // We want this service to continue running until it is explicitly
462                 // stopped, so return sticky.
463                 return START_STICKY;
464         }
465
466         @Override
467         public void onDestroy() {
468
469                 // Stop listening for location updates
470                 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
471
472                 // Stop the bluetooth Comms threads
473                 disconnect(true);
474
475                 // Demote us from the foreground, and cancel the persistent notification.
476                 stopForeground(true);
477
478                 // Tell the user we stopped.
479                 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
480         }
481
482         @Override
483         public IBinder onBind(Intent intent) {
484                 return messenger.getBinder();
485         }
486
487
488         public void onLocationChanged(Location location) {
489                 telemetry_state.location = location;
490                 if (D) Log.d(TAG, "location changed");
491                 send_to_clients();
492         }
493
494         public void onStatusChanged(String provider, int status, Bundle extras) {
495         }
496
497         public void onProviderEnabled(String provider) {
498         }
499
500         public void onProviderDisabled(String provider) {
501         }
502
503 }