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