altosdroid: Remove a debug line in AltosVoice
[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                                 AltosDebug.debug("MSG_TELEMETRY");
203                                 s.telemetry((AltosTelemetry) msg.obj);
204                                 break;
205                         case MSG_CRC_ERROR:
206                                 // forward crc error messages
207                                 s.telemetry_state.crc_errors = (Integer) msg.obj;
208                                 AltosDebug.debug("MSG_CRC_ERROR");
209                                 s.send_to_clients();
210                                 break;
211                         default:
212                                 super.handleMessage(msg);
213                         }
214                 }
215         }
216
217         /* Handle telemetry packet
218          */
219         private void telemetry(AltosTelemetry telem) {
220                 AltosState      state;
221
222                 if (telemetry_state.states.containsKey(telem.serial))
223                         state = telemetry_state.states.get(telem.serial).clone();
224                 else
225                         state = new AltosState();
226                 telem.update_state(state);
227                 telemetry_state.states.put(telem.serial, state);
228                 if (state != null) {
229                         AltosDebug.debug("Save state %d", telem.serial);
230                         AltosPreferences.set_state(telem.serial, state, null);
231                 }
232                 send_to_clients();
233         }
234
235         /* Construct the message to deliver to clients
236          */
237         private Message message() {
238                 if (telemetry_state == null)
239                         AltosDebug.debug("telemetry_state null!");
240                 if (telemetry_state.states == null)
241                         AltosDebug.debug("telemetry_state.states null!");
242                 return Message.obtain(null, AltosDroid.MSG_STATE, telemetry_state);
243         }
244
245         /* A new friend has connected
246          */
247         private void add_client(Messenger client) {
248
249                 clients.add(client);
250                 AltosDebug.debug("Client bound to service");
251
252                 /* On connect, send the current state to the new client
253                  */
254                 send_to_client(client, message());
255
256                 /* If we've got an address from a previous session, then
257                  * go ahead and try to reconnect to the device
258                  */
259                 if (address != null && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
260                         AltosDebug.debug("Reconnecting now...");
261                         start_altos_bluetooth(address, false);
262                 }
263         }
264
265         /* A client has disconnected, clean up
266          */
267         private void remove_client(Messenger client) {
268                 clients.remove(client);
269                 AltosDebug.debug("Client unbound from service");
270
271                 /* When the list of clients is empty, stop the service if
272                  * we have no current telemetry source
273                  */
274
275                  if (clients.isEmpty() && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
276                          AltosDebug.debug("No clients, no connection. Stopping\n");
277                          stopSelf();
278                  }
279         }
280
281         private void send_to_client(Messenger client, Message m) {
282                 try {
283                         AltosDebug.debug("Send message to client %s", client.toString());
284                         client.send(m);
285                 } catch (RemoteException e) {
286                         AltosDebug.error("Client %s disappeared", client.toString());
287                         remove_client(client);
288                 }
289         }
290
291         private void send_to_clients() {
292                 Message m = message();
293                 AltosDebug.debug("Send message to %d clients", clients.size());
294                 for (Messenger client : clients)
295                         send_to_client(client, m);
296         }
297
298         private void disconnect(boolean notify) {
299                 AltosDebug.debug("disconnect(): begin");
300
301                 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
302                 telemetry_state.address = null;
303
304                 if (altos_link != null)
305                         altos_link.closing();
306
307                 stop_receiver_voltage_timer();
308
309                 if (telemetry_reader != null) {
310                         AltosDebug.debug("disconnect(): stopping TelemetryReader");
311                         telemetry_reader.interrupt();
312                         try {
313                                 telemetry_reader.join();
314                         } catch (InterruptedException e) {
315                         }
316                         telemetry_reader = null;
317                 }
318                 if (telemetry_logger != null) {
319                         AltosDebug.debug("disconnect(): stopping TelemetryLogger");
320                         telemetry_logger.stop();
321                         telemetry_logger = null;
322                 }
323                 if (altos_link != null) {
324                         AltosDebug.debug("disconnect(): stopping AltosDroidLink");
325                         altos_link.close();
326                         altos_link = null;
327                 }
328                 telemetry_state.config = null;
329                 if (notify) {
330                         AltosDebug.debug("disconnect(): send message to clients");
331                         send_to_clients();
332                         if (clients.isEmpty()) {
333                                 AltosDebug.debug("disconnect(): no clients, terminating");
334                                 stopSelf();
335                         }
336                 }
337         }
338
339         private void start_usb(UsbDevice device) {
340                 AltosUsb        d = new AltosUsb(this, device, handler);
341
342                 if (d != null) {
343                         disconnect(false);
344                         altos_link = d;
345                         try {
346                                 connected();
347                         } catch (InterruptedException ie) {
348                         }
349                 }
350         }
351
352         private void delete_serial(int serial) {
353                 telemetry_state.states.remove((Integer) serial);
354                 AltosPreferences.remove_state(serial);
355                 send_to_clients();
356         }
357
358         private void start_altos_bluetooth(DeviceAddress address, boolean pause) {
359                 // Get the BLuetoothDevice object
360                 BluetoothDevice device = bluetooth_adapter.getRemoteDevice(address.address);
361
362                 disconnect(false);
363                 this.address = address;
364                 AltosDebug.debug("start_altos_bluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress());
365                 altos_link = new AltosBluetooth(device, handler, pause);
366                 telemetry_state.connect = TelemetryState.CONNECT_CONNECTING;
367                 telemetry_state.address = address;
368                 send_to_clients();
369         }
370
371         // Timer for receiver battery voltage monitoring
372         Timer receiver_voltage_timer;
373
374         private void update_receiver_voltage() {
375                 if (altos_link != null) {
376                         try {
377                                 double  voltage = altos_link.monitor_battery();
378                                 AltosDebug.debug("update receiver voltage %g\n", voltage);
379                                 telemetry_state.receiver_battery = voltage;
380                         } catch (InterruptedException ie) {
381                         }
382                 }
383         }
384
385         private void stop_receiver_voltage_timer() {
386                 if (receiver_voltage_timer != null) {
387                         receiver_voltage_timer.cancel();
388                         receiver_voltage_timer.purge();
389                         receiver_voltage_timer = null;
390                 }
391         }
392
393         private void start_receiver_voltage_timer() {
394                 if (receiver_voltage_timer == null && altos_link.has_monitor_battery()) {
395                         receiver_voltage_timer = new Timer();
396                         receiver_voltage_timer.scheduleAtFixedRate(new TimerTask() { public void run() {update_receiver_voltage();}}, 1000L, 10000L);
397                 }
398         }
399
400         private void connected() throws InterruptedException {
401                 AltosDebug.debug("connected top");
402                 AltosDebug.check_ui("connected\n");
403                 try {
404                         if (altos_link == null)
405                                 throw new InterruptedException("no bluetooth");
406                         telemetry_state.config = altos_link.config_data();
407                         altos_link.set_radio_frequency(telemetry_state.frequency);
408                         altos_link.set_telemetry_rate(telemetry_state.telemetry_rate);
409                 } catch (TimeoutException e) {
410                         // If this timed out, then we really want to retry it, but
411                         // probably safer to just retry the connection from scratch.
412                         AltosDebug.debug("connected timeout");
413                         if (address != null) {
414                                 AltosDebug.debug("connected timeout, retrying");
415                                 start_altos_bluetooth(address, true);
416                         } else {
417                                 handler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
418                                 disconnect(true);
419                         }
420                         return;
421                 }
422
423                 AltosDebug.debug("connected bluetooth configured");
424                 telemetry_state.connect = TelemetryState.CONNECT_CONNECTED;
425                 telemetry_state.address = address;
426
427                 telemetry_reader = new TelemetryReader(altos_link, handler);
428                 telemetry_reader.start();
429
430                 AltosDebug.debug("connected TelemetryReader started");
431
432                 telemetry_logger = new TelemetryLogger(this, altos_link);
433
434                 start_receiver_voltage_timer();
435
436                 AltosDebug.debug("Notify UI of connection");
437
438                 send_to_clients();
439         }
440
441
442         @Override
443         public void onCreate() {
444
445                 AltosDebug.init(this);
446
447                 // Initialise preferences
448                 AltosDroidPreferences.init(this);
449
450                 // Get local Bluetooth adapter
451                 bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
452
453                 // If the adapter is null, then Bluetooth is not supported
454                 if (bluetooth_adapter == null) {
455                         Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
456                 }
457
458                 telemetry_state = new TelemetryState();
459
460                 // Create a reference to the NotificationManager so that we can update our notifcation text later
461                 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
462
463                 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
464                 telemetry_state.address = null;
465
466                 /* Pull the saved state information out of the preferences database
467                  */
468                 ArrayList<Integer> serials = AltosPreferences.list_states();
469
470                 telemetry_state.latest_serial = AltosPreferences.latest_state();
471
472                 for (int serial : serials) {
473                         AltosSavedState saved_state = AltosPreferences.state(serial);
474                         if (saved_state != null) {
475                                 if (serial == 0) {
476                                         serial = saved_state.state.serial;
477                                         AltosPreferences.set_state(serial, saved_state.state, saved_state.listener_state);
478                                         AltosPreferences.remove_state(0);
479                                 }
480                                 if (telemetry_state.latest_serial == 0)
481                                         telemetry_state.latest_serial = serial;
482
483                                 AltosDebug.debug("recovered old state serial %d flight %d\n",
484                                                  serial,
485                                                  saved_state.state.flight);
486                                 if (saved_state.state.gps != null)
487                                         AltosDebug.debug("\tposition %f,%f\n",
488                                                          saved_state.state.gps.lat,
489                                                          saved_state.state.gps.lon);
490                                 telemetry_state.states.put(serial, saved_state.state);
491                         }
492                 }
493
494                 // Listen for GPS and Network position updates
495                 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
496
497                 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
498         }
499
500         @Override
501         public int onStartCommand(Intent intent, int flags, int startId) {
502                 AltosDebug.debug("Received start id %d: %s", startId, intent);
503
504                 CharSequence text = getText(R.string.telemetry_service_started);
505
506                 // Create notification to be displayed while the service runs
507                 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
508
509                 // The PendingIntent to launch our activity if the user selects this notification
510                 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
511                                 new Intent(this, AltosDroid.class), 0);
512
513                 // Set the info for the views that show in the notification panel.
514                 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
515
516                 // Set the notification to be in the "Ongoing" section.
517                 notification.flags |= Notification.FLAG_ONGOING_EVENT;
518
519                 // Move us into the foreground.
520                 startForeground(NOTIFICATION, notification);
521
522                 if (intent != null) {
523                         String  action = intent.getAction();
524
525                         if (action.equals(AltosDroid.ACTION_BLUETOOTH)) {
526                                 DeviceAddress address = AltosDroidPreferences.active_device();
527                                 if (address != null && !address.address.startsWith("USB"))
528                                         start_altos_bluetooth(address, false);
529                         }
530                 }
531
532                 // We want this service to continue running until it is explicitly
533                 // stopped, so return sticky.
534                 return START_STICKY;
535         }
536
537         @Override
538         public void onDestroy() {
539
540                 // Stop listening for location updates
541                 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
542
543                 // Stop the bluetooth Comms threads
544                 disconnect(true);
545
546                 // Demote us from the foreground, and cancel the persistent notification.
547                 stopForeground(true);
548
549                 // Tell the user we stopped.
550                 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
551         }
552
553         @Override
554         public IBinder onBind(Intent intent) {
555                 return messenger.getBinder();
556         }
557
558
559         public void onLocationChanged(Location location) {
560                 telemetry_state.location = location;
561                 AltosDebug.debug("location changed");
562                 send_to_clients();
563         }
564
565         public void onStatusChanged(String provider, int status, Bundle extras) {
566         }
567
568         public void onProviderEnabled(String provider) {
569         }
570
571         public void onProviderDisabled(String provider) {
572         }
573
574 }