36ba03084cd931163221ed2bad6e9b1291076538
[fw/altos] / altosdroid / src / org / altusmetrum / AltosDroid / AltosDroid.java
1 /*
2  * Copyright © 2012-2013 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; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
17  */
18
19 package org.altusmetrum.AltosDroid;
20
21 import java.lang.ref.WeakReference;
22 import java.text.*;
23 import java.util.*;
24 import java.io.*;
25
26 import android.app.Activity;
27 import android.app.PendingIntent;
28 import android.bluetooth.BluetoothAdapter;
29 import android.bluetooth.BluetoothDevice;
30 import android.content.Intent;
31 import android.content.Context;
32 import android.content.ComponentName;
33 import android.content.ServiceConnection;
34 import android.content.DialogInterface;
35 import android.os.IBinder;
36 import android.os.Bundle;
37 import android.os.Handler;
38 import android.os.Message;
39 import android.os.Messenger;
40 import android.os.RemoteException;
41 import android.content.res.Resources;
42 import android.support.v4.app.FragmentActivity;
43 import android.support.v4.app.FragmentManager;
44 import android.util.DisplayMetrics;
45 import android.view.*;
46 import android.widget.*;
47 import android.app.AlertDialog;
48 import android.location.Location;
49 import android.location.LocationManager;
50 import android.location.LocationListener;
51 import android.hardware.usb.*;
52 import android.graphics.*;
53 import android.graphics.drawable.*;
54
55 import org.altusmetrum.altoslib_11.*;
56
57 class SavedState {
58         long    received_time;
59         int     state;
60         boolean locked;
61         String  callsign;
62         int     serial;
63         int     flight;
64         int     rssi;
65
66         SavedState(AltosState state) {
67                 received_time = state.received_time;
68                 this.state = state.state();
69                 if (state.gps != null)
70                         locked = state.gps.locked;
71                 else
72                         locked = false;
73                 callsign = state.cal_data.callsign;
74                 serial = state.cal_data.serial;
75                 flight = state.cal_data.flight;
76                 rssi = state.rssi;
77         }
78 }
79
80 public class AltosDroid extends FragmentActivity implements AltosUnitsListener, LocationListener {
81
82         // Actions sent to the telemetry server at startup time
83
84         public static final String ACTION_BLUETOOTH = "org.altusmetrum.AltosDroid.BLUETOOTH";
85         public static final String ACTION_USB = "org.altusmetrum.AltosDroid.USB";
86
87         // Message types received by our Handler
88
89         public static final int MSG_STATE           = 1;
90         public static final int MSG_UPDATE_AGE      = 2;
91         public static final int MSG_IDLE_MODE       = 3;
92         public static final int MSG_IGNITER_STATUS  = 4;
93
94         // Intent request codes
95         public static final int REQUEST_CONNECT_DEVICE = 1;
96         public static final int REQUEST_ENABLE_BT      = 2;
97         public static final int REQUEST_PRELOAD_MAPS   = 3;
98         public static final int REQUEST_IDLE_MODE      = 5;
99         public static final int REQUEST_IGNITERS       = 6;
100         public static final int REQUEST_SETUP          = 7;
101
102         public static final String EXTRA_IDLE_MODE = "idle_mode";
103         public static final String EXTRA_IDLE_RESULT = "idle_result";
104         public static final String EXTRA_TELEMETRY_SERVICE = "telemetry_service";
105
106         // Setup result bits
107         public static final int SETUP_BAUD = 1;
108         public static final int SETUP_UNITS = 2;
109         public static final int SETUP_MAP_SOURCE = 4;
110         public static final int SETUP_MAP_TYPE = 8;
111
112         public static FragmentManager   fm;
113
114         private BluetoothAdapter mBluetoothAdapter = null;
115
116         // Flight state values
117         private TextView mCallsignView;
118         private TextView mRSSIView;
119         private TextView mSerialView;
120         private TextView mFlightView;
121         private RelativeLayout mStateLayout;
122         private TextView mStateView;
123         private TextView mAgeView;
124         private boolean  mAgeViewOld;
125         private int mAgeNewColor;
126         private int mAgeOldColor;
127
128         public static final String      tab_pad_name = "pad";
129         public static final String      tab_flight_name = "flight";
130         public static final String      tab_recover_name = "recover";
131         public static final String      tab_map_name = "map";
132
133         // field to display the version at the bottom of the screen
134         private TextView mVersion;
135
136         private boolean idle_mode = false;
137
138         public Location location = null;
139
140         private AltosState      state;
141         private SavedState      saved_state;
142
143         // Tabs
144         TabHost         mTabHost;
145         AltosViewPager  mViewPager;
146         TabsAdapter     mTabsAdapter;
147         ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
148         int             tabHeight;
149
150         // Timer and Saved flight state for Age calculation
151         private Timer timer;
152
153         TelemetryState  telemetry_state;
154         Integer[]       serials;
155
156         UsbDevice       pending_usb_device;
157         boolean         start_with_usb;
158
159         // Service
160         private boolean mIsBound   = false;
161         private Messenger mService = null;
162         final Messenger mMessenger = new Messenger(new IncomingHandler(this));
163
164         // Text to Speech
165         private AltosVoice mAltosVoice = null;
166
167         // The Handler that gets information back from the Telemetry Service
168         static class IncomingHandler extends Handler {
169                 private final WeakReference<AltosDroid> mAltosDroid;
170                 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
171
172                 @Override
173                 public void handleMessage(Message msg) {
174                         AltosDroid ad = mAltosDroid.get();
175
176                         switch (msg.what) {
177                         case MSG_STATE:
178                                 if (msg.obj == null) {
179                                         AltosDebug.debug("telemetry_state null!");
180                                         return;
181                                 }
182                                 ad.update_state((TelemetryState) msg.obj);
183                                 break;
184                         case MSG_UPDATE_AGE:
185                                 ad.update_age();
186                                 break;
187                         case MSG_IDLE_MODE:
188                                 ad.idle_mode = (Boolean) msg.obj;
189                                 ad.update_state(null);
190                                 break;
191                         }
192                 }
193         };
194
195
196         private ServiceConnection mConnection = new ServiceConnection() {
197                 public void onServiceConnected(ComponentName className, IBinder service) {
198                         mService = new Messenger(service);
199                         try {
200                                 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
201                                 msg.replyTo = mMessenger;
202                                 mService.send(msg);
203                         } catch (RemoteException e) {
204                                 // In this case the service has crashed before we could even do anything with it
205                         }
206                         if (pending_usb_device != null) {
207                                 try {
208                                         mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, pending_usb_device));
209                                         pending_usb_device = null;
210                                 } catch (RemoteException e) {
211                                 }
212                         }
213                 }
214
215                 public void onServiceDisconnected(ComponentName className) {
216                         // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
217                         mService = null;
218                 }
219         };
220
221         void doBindService() {
222                 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
223                 mIsBound = true;
224         }
225
226         void doUnbindService() {
227                 if (mIsBound) {
228                         // If we have received the service, and hence registered with it, then now is the time to unregister.
229                         if (mService != null) {
230                                 try {
231                                         Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
232                                         msg.replyTo = mMessenger;
233                                         mService.send(msg);
234                                 } catch (RemoteException e) {
235                                         // There is nothing special we need to do if the service has crashed.
236                                 }
237                         }
238                         // Detach our existing connection.
239                         unbindService(mConnection);
240                         mIsBound = false;
241                 }
242         }
243
244         public void registerTab(AltosDroidTab mTab) {
245                 mTabs.add(mTab);
246         }
247
248         public void unregisterTab(AltosDroidTab mTab) {
249                 mTabs.remove(mTab);
250         }
251
252         public void units_changed(boolean imperial_units) {
253                 for (AltosDroidTab mTab : mTabs)
254                         mTab.units_changed(imperial_units);
255         }
256
257         void update_title(TelemetryState telemetry_state) {
258                 switch (telemetry_state.connect) {
259                 case TelemetryState.CONNECT_CONNECTED:
260                         if (telemetry_state.config != null) {
261                                 String str = String.format("S/N %d %6.3f MHz%s", telemetry_state.config.serial,
262                                                            telemetry_state.frequency, idle_mode ? " (idle)" : "");
263                                 if (telemetry_state.telemetry_rate != AltosLib.ao_telemetry_rate_38400)
264                                         str = str.concat(String.format(" %d bps",
265                                                                        AltosLib.ao_telemetry_rate_values[telemetry_state.telemetry_rate]));
266                                 setTitle(str);
267                         } else {
268                                 setTitle(R.string.title_connected_to);
269                         }
270                         break;
271                 case TelemetryState.CONNECT_CONNECTING:
272                         if (telemetry_state.address != null)
273                                 setTitle(String.format("Connecting to %s...", telemetry_state.address.name));
274                         else
275                                 setTitle("Connecting to something...");
276                         break;
277                 case TelemetryState.CONNECT_DISCONNECTED:
278                 case TelemetryState.CONNECT_NONE:
279                         setTitle(R.string.title_not_connected);
280                         break;
281                 }
282         }
283
284         void start_timer() {
285                 if (timer == null) {
286                         timer = new Timer();
287                         timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 1000L);
288                 }
289         }
290
291         void stop_timer() {
292                 if (timer != null) {
293                         timer.cancel();
294                         timer.purge();
295                         timer = null;
296                 }
297         }
298
299         int     selected_serial = 0;
300         int     current_serial;
301         long    switch_time;
302
303         void set_switch_time() {
304                 switch_time = System.currentTimeMillis();
305                 selected_serial = 0;
306         }
307
308         boolean registered_units_listener;
309
310         void update_state(TelemetryState new_telemetry_state) {
311
312                 if (new_telemetry_state != null)
313                         telemetry_state = new_telemetry_state;
314
315                 if (selected_serial != 0)
316                         current_serial = selected_serial;
317
318                 if (current_serial == 0)
319                         current_serial = telemetry_state.latest_serial;
320
321                 if (!registered_units_listener) {
322                         registered_units_listener = true;
323                         AltosPreferences.register_units_listener(this);
324                 }
325
326                 serials = telemetry_state.states.keySet().toArray(new Integer[0]);
327                 Arrays.sort(serials);
328
329                 update_title(telemetry_state);
330
331                 AltosState      state = null;
332                 boolean         aged = true;
333
334                 if (telemetry_state.states.containsKey(current_serial)) {
335                         state = telemetry_state.states.get(current_serial);
336                         int age = state_age(state.received_time);
337                         if (age < 20)
338                                 aged = false;
339                         if (current_serial == selected_serial)
340                                 aged = false;
341                         else if (switch_time != 0 && (switch_time - state.received_time) > 0)
342                                 aged = true;
343                 }
344
345                 if (aged) {
346                         AltosState      newest_state = null;
347                         int             newest_age = 0;
348
349                         for (int serial : telemetry_state.states.keySet()) {
350                                 AltosState      existing = telemetry_state.states.get(serial);
351                                 int             existing_age = state_age(existing.received_time);
352
353                                 if (newest_state == null || existing_age < newest_age) {
354                                         newest_state = existing;
355                                         newest_age = existing_age;
356                                 }
357                         }
358
359                         if (newest_state != null)
360                                 state = newest_state;
361                 }
362
363                 update_ui(telemetry_state, state, telemetry_state.quiet);
364
365                 start_timer();
366         }
367
368         boolean same_string(String a, String b) {
369                 if (a == null) {
370                         if (b == null)
371                                 return true;
372                         return false;
373                 } else {
374                         if (b == null)
375                                 return false;
376                         return a.equals(b);
377                 }
378         }
379
380
381         private int blend_component(int a, int b, double r, int shift, int mask) {
382                 return ((int) (((a >> shift) & mask) * r + ((b >> shift) & mask) * (1 - r)) & mask) << shift;
383         }
384         private int blend_color(int a, int b, double r) {
385                 return (blend_component(a, b, r, 0, 0xff) |
386                         blend_component(a, b, r, 8, 0xff) |
387                         blend_component(a, b, r, 16, 0xff) |
388                         blend_component(a, b, r, 24, 0xff));
389         }
390
391         int state_age(long received_time) {
392                 return (int) ((System.currentTimeMillis() - received_time + 500) / 1000);
393         }
394
395         void set_screen_on(int age) {
396                 if (age < 60)
397                         getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
398                 else
399                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
400         }
401
402         void update_age() {
403                 if (saved_state != null) {
404                         int age = state_age(saved_state.received_time);
405
406                         double age_scale = age / 100.0;
407
408                         if (age_scale > 1.0)
409                                 age_scale = 1.0;
410
411                         mAgeView.setTextColor(blend_color(mAgeOldColor, mAgeNewColor, age_scale));
412
413                         set_screen_on(age);
414
415                         String  text;
416                         if (age < 60)
417                                 text = String.format("%ds", age);
418                         else if (age < 60 * 60)
419                                 text = String.format("%dm", age / 60);
420                         else if (age < 60 * 60 * 24)
421                                 text = String.format("%dh", age / (60 * 60));
422                         else
423                                 text = String.format("%dd", age / (24 * 60 * 60));
424                         mAgeView.setText(text);
425                 }
426         }
427
428         void update_ui(TelemetryState telem_state, AltosState state, boolean quiet) {
429
430                 this.state = state;
431
432                 int prev_state = AltosLib.ao_flight_invalid;
433
434                 AltosGreatCircle from_receiver = null;
435
436                 if (saved_state != null)
437                         prev_state = saved_state.state;
438
439                 if (state != null) {
440                         set_screen_on(state_age(state.received_time));
441
442                         if (state.state() == AltosLib.ao_flight_stateless) {
443                                 boolean prev_locked = false;
444                                 boolean locked = false;
445
446                                 if(state.gps != null)
447                                         locked = state.gps.locked;
448                                 if (saved_state != null)
449                                         prev_locked = saved_state.locked;
450                                 if (prev_locked != locked) {
451                                         String currentTab = mTabHost.getCurrentTabTag();
452                                         if (locked) {
453                                                 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
454                                         } else {
455                                                 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_pad_name);
456                                         }
457                                 }
458                         } else {
459                                 if (prev_state != state.state()) {
460                                         String currentTab = mTabHost.getCurrentTabTag();
461                                         switch (state.state()) {
462                                         case AltosLib.ao_flight_boost:
463                                                 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
464                                                 break;
465                                         case AltosLib.ao_flight_landed:
466                                                 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_recover_name);
467                                                 break;
468                                         case AltosLib.ao_flight_stateless:
469                                                 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
470                                                 break;
471                                         }
472                                 }
473                         }
474
475                         if (location != null && state.gps != null && state.gps.locked) {
476                                 double altitude = 0;
477                                 if (location.hasAltitude())
478                                         altitude = location.getAltitude();
479                                 from_receiver = new AltosGreatCircle(location.getLatitude(),
480                                                                      location.getLongitude(),
481                                                                      altitude,
482                                                                      state.gps.lat,
483                                                                      state.gps.lon,
484                                                                      state.gps.alt);
485                         }
486
487                         if (saved_state == null || !same_string(saved_state.callsign, state.cal_data.callsign)) {
488                                 mCallsignView.setText(state.cal_data.callsign);
489                         }
490                         if (saved_state == null || state.cal_data.serial != saved_state.serial) {
491                                 if (state.cal_data.serial == AltosLib.MISSING)
492                                         mSerialView.setText("");
493                                 else
494                                         mSerialView.setText(String.format("%d", state.cal_data.serial));
495                         }
496                         if (saved_state == null || state.cal_data.flight != saved_state.flight) {
497                                 if (state.cal_data.flight == AltosLib.MISSING)
498                                         mFlightView.setText("");
499                                 else
500                                         mFlightView.setText(String.format("%d", state.cal_data.flight));
501                         }
502                         if (saved_state == null || state.state() != saved_state.state) {
503                                 if (state.state() == AltosLib.ao_flight_stateless) {
504                                         mStateLayout.setVisibility(View.GONE);
505                                 } else {
506                                         mStateView.setText(state.state_name());
507                                         mStateLayout.setVisibility(View.VISIBLE);
508                                 }
509                         }
510                         if (saved_state == null || state.rssi != saved_state.rssi) {
511                                 if (state.rssi == AltosLib.MISSING)
512                                         mRSSIView.setText("");
513                                 else
514                                         mRSSIView.setText(String.format("%d", state.rssi));
515                         }
516                         saved_state = new SavedState(state);
517                 }
518
519                 for (AltosDroidTab mTab : mTabs)
520                         mTab.update_ui(telem_state, state, from_receiver, location, mTab == mTabsAdapter.currentItem());
521
522                 AltosDebug.debug("quiet %b\n", quiet);
523                 if (mAltosVoice != null)
524                         mAltosVoice.tell(telem_state, state, from_receiver, location, (AltosDroidTab) mTabsAdapter.currentItem(), quiet);
525
526         }
527
528         private void onTimerTick() {
529                 try {
530                         mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
531                 } catch (RemoteException e) {
532                 }
533         }
534
535         static String pos(double p, String pos, String neg) {
536                 String  h = pos;
537                 if (p == AltosLib.MISSING)
538                         return "";
539                 if (p < 0) {
540                         h = neg;
541                         p = -p;
542                 }
543                 int deg = (int) Math.floor(p);
544                 double min = (p - Math.floor(p)) * 60.0;
545                 return String.format("%d°%9.4f\" %s", deg, min, h);
546         }
547
548         static String number(String format, double value) {
549                 if (value == AltosLib.MISSING)
550                         return "";
551                 return String.format(format, value);
552         }
553
554         static String integer(String format, int value) {
555                 if (value == AltosLib.MISSING)
556                         return "";
557                 return String.format(format, value);
558         }
559
560         private View create_tab_view(String label) {
561                 LayoutInflater inflater = (LayoutInflater) this.getLayoutInflater();
562                 View tab_view = inflater.inflate(R.layout.tab_layout, null);
563                 TextView text_view = (TextView) tab_view.findViewById (R.id.tabLabel);
564                 text_view.setText(label);
565                 return tab_view;
566         }
567
568         @Override
569         public void onCreate(Bundle savedInstanceState) {
570                 super.onCreate(savedInstanceState);
571                 AltosDebug.init(this);
572                 AltosDebug.debug("+++ ON CREATE +++");
573
574                 // Initialise preferences
575                 AltosDroidPreferences.init(this);
576
577                 fm = getSupportFragmentManager();
578
579                 // Set up the window layout
580                 setContentView(R.layout.altosdroid);
581
582                 // Create the Tabs and ViewPager
583                 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
584                 mTabHost.setup();
585
586                 mViewPager = (AltosViewPager)findViewById(R.id.pager);
587                 mViewPager.setOffscreenPageLimit(4);
588
589                 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
590
591                 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_pad_name).setIndicator(create_tab_view("Pad")), TabPad.class, null);
592                 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_flight_name).setIndicator(create_tab_view("Flight")), TabFlight.class, null);
593                 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_recover_name).setIndicator(create_tab_view("Recover")), TabRecover.class, null);
594                 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_map_name).setIndicator(create_tab_view("Map")), TabMap.class, null);
595
596                 // Display the Version
597                 mVersion = (TextView) findViewById(R.id.version);
598                 mVersion.setText("Version: " + BuildInfo.version +
599                                  (AltosVersion.has_google_maps_api_key() ? " maps" : "") +
600                                  " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
601                                  " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
602
603                 mCallsignView  = (TextView) findViewById(R.id.callsign_value);
604                 mRSSIView      = (TextView) findViewById(R.id.rssi_value);
605                 mSerialView    = (TextView) findViewById(R.id.serial_value);
606                 mFlightView    = (TextView) findViewById(R.id.flight_value);
607                 mStateLayout   = (RelativeLayout) findViewById(R.id.state_container);
608                 mStateView     = (TextView) findViewById(R.id.state_value);
609                 mAgeView       = (TextView) findViewById(R.id.age_value);
610                 mAgeNewColor   = mAgeView.getTextColors().getDefaultColor();
611                 mAgeOldColor   = getResources().getColor(R.color.old_color);
612         }
613
614         private void ensureBluetooth() {
615                 // Get local Bluetooth adapter
616                 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
617
618                 /* if there is a BT adapter and it isn't turned on, then turn it on */
619                 if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
620                         Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
621                         startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
622                 }
623         }
624
625         private boolean check_usb() {
626                 UsbDevice       device = AltosUsb.find_device(this, AltosLib.product_basestation);
627
628                 if (device != null) {
629                         Intent          i = new Intent(this, AltosDroid.class);
630                         PendingIntent   pi = PendingIntent.getActivity(this, 0, new Intent("hello world", null, this, AltosDroid.class), 0);
631
632                         if (AltosUsb.request_permission(this, device, pi)) {
633                                 connectUsb(device);
634                         }
635                         start_with_usb = true;
636                         return true;
637                 }
638
639                 start_with_usb = false;
640
641                 return false;
642         }
643
644         private void noticeIntent(Intent intent) {
645
646                 /* Ok, this is pretty convenient.
647                  *
648                  * When a USB device is plugged in, and our 'hotplug'
649                  * intent registration fires, we get an Intent with
650                  * EXTRA_DEVICE set.
651                  *
652                  * When we start up and see a usb device and request
653                  * permission to access it, that queues a
654                  * PendingIntent, which has the EXTRA_DEVICE added in,
655                  * along with the EXTRA_PERMISSION_GRANTED field as
656                  * well.
657                  *
658                  * So, in both cases, we get the device name using the
659                  * same call. We check to see if access was granted,
660                  * in which case we ignore the device field and do our
661                  * usual startup thing.
662                  */
663
664                 UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
665                 boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
666
667                 AltosDebug.debug("intent %s device %s granted %s", intent, device, granted);
668
669                 if (!granted)
670                         device = null;
671
672                 if (device != null) {
673                         AltosDebug.debug("intent has usb device " + device.toString());
674                         connectUsb(device);
675                 } else {
676
677                         /* 'granted' is only false if this intent came
678                          * from the request_permission call and
679                          * permission was denied. In which case, we
680                          * don't want to loop forever...
681                          */
682                         if (granted) {
683                                 AltosDebug.debug("check for a USB device at startup");
684                                 if (check_usb())
685                                         return;
686                         }
687                         AltosDebug.debug("Starting by looking for bluetooth devices");
688                         ensureBluetooth();
689                 }
690         }
691
692         @Override
693         public void onStart() {
694                 super.onStart();
695                 AltosDebug.debug("++ ON START ++");
696
697                 set_switch_time();
698
699                 noticeIntent(getIntent());
700
701                 // Start Telemetry Service
702                 String  action = start_with_usb ? ACTION_USB : ACTION_BLUETOOTH;
703
704                 startService(new Intent(action, null, AltosDroid.this, TelemetryService.class));
705
706                 doBindService();
707
708                 if (mAltosVoice == null)
709                         mAltosVoice = new AltosVoice(this);
710
711         }
712
713         @Override
714         public void onNewIntent(Intent intent) {
715                 super.onNewIntent(intent);
716                 AltosDebug.debug("onNewIntent");
717                 noticeIntent(intent);
718         }
719
720         @Override
721         public void onResume() {
722                 super.onResume();
723                 AltosDebug.debug("+ ON RESUME +");
724
725                 // Listen for GPS and Network position updates
726                 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
727                 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
728
729                 location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
730
731                 if (location != null)
732                         AltosDebug.debug("Resume, location is %f,%f\n",
733                                          location.getLatitude(),
734                                          location.getLongitude());
735
736                 update_ui(telemetry_state, state, true);
737         }
738
739         @Override
740         public void onPause() {
741                 super.onPause();
742                 AltosDebug.debug("- ON PAUSE -");
743                 // Stop listening for location updates
744                 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
745         }
746
747         @Override
748         public void onStop() {
749                 super.onStop();
750                 AltosDebug.debug("-- ON STOP --");
751         }
752
753         @Override
754         public void onDestroy() {
755                 super.onDestroy();
756                 AltosDebug.debug("--- ON DESTROY ---");
757
758                 doUnbindService();
759                 if (mAltosVoice != null) {
760                         mAltosVoice.stop();
761                         mAltosVoice = null;
762                 }
763                 stop_timer();
764         }
765
766         protected void onActivityResult(int requestCode, int resultCode, Intent data) {
767                 AltosDebug.debug("onActivityResult " + resultCode);
768                 switch (requestCode) {
769                 case REQUEST_CONNECT_DEVICE:
770                         // When DeviceListActivity returns with a device to connect to
771                         if (resultCode == Activity.RESULT_OK) {
772                                 connectDevice(data);
773                         }
774                         break;
775                 case REQUEST_ENABLE_BT:
776                         // When the request to enable Bluetooth returns
777                         if (resultCode == Activity.RESULT_OK) {
778                                 // Bluetooth is now enabled, so set up a chat session
779                                 //setupChat();
780                                 AltosDebug.debug("BT enabled");
781                                 bluetoothEnabled(data);
782                         } else {
783                                 // User did not enable Bluetooth or an error occured
784                                 AltosDebug.debug("BT not enabled");
785                         }
786                         break;
787                 case REQUEST_IDLE_MODE:
788                         if (resultCode == Activity.RESULT_OK)
789                                 idle_mode(data);
790                         break;
791                 case REQUEST_IGNITERS:
792                         break;
793                 case REQUEST_SETUP:
794                         if (resultCode == Activity.RESULT_OK)
795                                 note_setup_changes(data);
796                         break;
797                 }
798         }
799
800         private void note_setup_changes(Intent data) {
801                 int changes = data.getIntExtra(SetupActivity.EXTRA_SETUP_CHANGES, 0);
802
803                 if ((changes & SETUP_BAUD) != 0) {
804                         try {
805                                 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD,
806                                                              AltosPreferences.telemetry_rate(1)));
807                         } catch (RemoteException re) {
808                         }
809                 }
810                 if ((changes & SETUP_UNITS) != 0) {
811                         /* nothing to do here */
812                 }
813                 if ((changes & SETUP_MAP_SOURCE) != 0) {
814                         /* nothing to do here */
815                 }
816                 if ((changes & SETUP_MAP_TYPE) != 0) {
817                         /* nothing to do here */
818                 }
819                 set_switch_time();
820         }
821
822         private void connectUsb(UsbDevice device) {
823                 if (mService == null)
824                         pending_usb_device = device;
825                 else {
826                         // Attempt to connect to the device
827                         try {
828                                 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, device));
829                                 AltosDebug.debug("Sent OPEN_USB message");
830                         } catch (RemoteException e) {
831                                 AltosDebug.debug("connect device message failed");
832                         }
833                 }
834         }
835
836         private void bluetoothEnabled(Intent data) {
837                 try {
838                         mService.send(Message.obtain(null, TelemetryService.MSG_BLUETOOTH_ENABLED, null));
839                 } catch (RemoteException e) {
840                         AltosDebug.debug("send BT enabled message failed");
841                 }
842         }
843
844         private void connectDevice(Intent data) {
845                 // Attempt to connect to the device
846                 try {
847                         String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
848                         String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
849
850                         AltosDebug.debug("Connecting to " + address + " " + name);
851                         DeviceAddress   a = new DeviceAddress(address, name);
852                         mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
853                         AltosDebug.debug("Sent connecting message");
854                 } catch (RemoteException e) {
855                         AltosDebug.debug("connect device message failed");
856                 }
857         }
858
859         private void disconnectDevice(boolean remember) {
860                 try {
861                         mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, (Boolean) remember));
862                 } catch (RemoteException e) {
863                 }
864         }
865
866         private void idle_mode(Intent data) {
867                 int type = data.getIntExtra(IdleModeActivity.EXTRA_IDLE_RESULT, -1);
868                 Message msg;
869
870                 AltosDebug.debug("intent idle_mode %d", type);
871                 switch (type) {
872                 case IdleModeActivity.IDLE_MODE_CONNECT:
873                         msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_START);
874                         try {
875                                 mService.send(msg);
876                         } catch (RemoteException re) {
877                         }
878                         break;
879                 case IdleModeActivity.IDLE_MODE_DISCONNECT:
880                         msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_STOP);
881                         try {
882                                 mService.send(msg);
883                         } catch (RemoteException re) {
884                         }
885                         break;
886                 case IdleModeActivity.IDLE_MODE_REBOOT:
887                         msg = Message.obtain(null, TelemetryService.MSG_REBOOT);
888                         try {
889                                 mService.send(msg);
890                         } catch (RemoteException re) {
891                         }
892                         break;
893                 case IdleModeActivity.IDLE_MODE_IGNITERS:
894                         Intent serverIntent = new Intent(this, IgniterActivity.class);
895                         startActivityForResult(serverIntent, REQUEST_IGNITERS);
896                         break;
897                 }
898         }
899
900         @Override
901         public boolean onCreateOptionsMenu(Menu menu) {
902                 MenuInflater inflater = getMenuInflater();
903                 inflater.inflate(R.menu.option_menu, menu);
904                 return true;
905         }
906
907         void setFrequency(double freq) {
908                 try {
909                         mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
910                         set_switch_time();
911                 } catch (RemoteException e) {
912                 }
913         }
914
915         void setFrequency(AltosFrequency frequency) {
916                 setFrequency (frequency.frequency);
917         }
918
919         void setBaud(int baud) {
920                 try {
921                         mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
922                         set_switch_time();
923                 } catch (RemoteException e) {
924                 }
925         }
926
927         void setBaud(String baud) {
928                 try {
929                         int     value = Integer.parseInt(baud);
930                         int     rate = AltosLib.ao_telemetry_rate_38400;
931                         switch (value) {
932                         case 2400:
933                                 rate = AltosLib.ao_telemetry_rate_2400;
934                                 break;
935                         case 9600:
936                                 rate = AltosLib.ao_telemetry_rate_9600;
937                                 break;
938                         case 38400:
939                                 rate = AltosLib.ao_telemetry_rate_38400;
940                                 break;
941                         }
942                         setBaud(rate);
943                 } catch (NumberFormatException e) {
944                 }
945         }
946
947         void select_tracker(int serial) {
948                 int i;
949
950                 AltosDebug.debug("select tracker %d\n", serial);
951
952                 if (serial == selected_serial) {
953                         AltosDebug.debug("%d already selected\n", serial);
954                         return;
955                 }
956
957                 if (serial != 0) {
958                         for (i = 0; i < serials.length; i++)
959                                 if (serials[i] == serial)
960                                         break;
961
962                         if (i == serials.length) {
963                                 AltosDebug.debug("attempt to select unknown tracker %d\n", serial);
964                                 return;
965                         }
966                 }
967
968                 current_serial = selected_serial = serial;
969                 update_state(null);
970         }
971
972         void touch_trackers(Integer[] serials) {
973                 AlertDialog.Builder builder_tracker = new AlertDialog.Builder(this);
974                 builder_tracker.setTitle("Select Tracker");
975                 final String[] trackers = new String[serials.length + 1];
976                 trackers[0] = "Auto";
977                 for (int i = 0; i < serials.length; i++)
978                         trackers[i+1] = String.format("%d", serials[i]);
979                 builder_tracker.setItems(trackers,
980                                          new DialogInterface.OnClickListener() {
981                                                  public void onClick(DialogInterface dialog, int item) {
982                                                          if (item == 0)
983                                                                  select_tracker(0);
984                                                          else
985                                                                  select_tracker(Integer.parseInt(trackers[item]));
986                                                  }
987                                          });
988                 AlertDialog alert_tracker = builder_tracker.create();
989                 alert_tracker.show();
990         }
991
992         void delete_track(int serial) {
993                 try {
994                         mService.send(Message.obtain(null, TelemetryService.MSG_DELETE_SERIAL, (Integer) serial));
995                 } catch (Exception ex) {
996                 }
997         }
998
999         @Override
1000         public boolean onOptionsItemSelected(MenuItem item) {
1001                 Intent serverIntent = null;
1002                 switch (item.getItemId()) {
1003                 case R.id.connect_scan:
1004                         ensureBluetooth();
1005                         // Launch the DeviceListActivity to see devices and do scan
1006                         serverIntent = new Intent(this, DeviceListActivity.class);
1007                         startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
1008                         return true;
1009                 case R.id.disconnect:
1010                         /* Disconnect the device
1011                          */
1012                         disconnectDevice(false);
1013                         return true;
1014                 case R.id.quit:
1015                         AltosDebug.debug("R.id.quit");
1016                         disconnectDevice(true);
1017                         finish();
1018                         return true;
1019                 case R.id.setup:
1020                         serverIntent = new Intent(this, SetupActivity.class);
1021                         startActivityForResult(serverIntent, REQUEST_SETUP);
1022                         return true;
1023                 case R.id.select_freq:
1024                         // Set the TBT radio frequency
1025
1026                         final AltosFrequency[] frequencies = AltosPreferences.common_frequencies();
1027                         String[] frequency_strings = new String[frequencies.length];
1028                         for (int i = 0; i < frequencies.length; i++)
1029                                 frequency_strings[i] = frequencies[i].toString();
1030
1031                         AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
1032                         builder_freq.setTitle("Pick a frequency");
1033                         builder_freq.setItems(frequency_strings,
1034                                          new DialogInterface.OnClickListener() {
1035                                                  public void onClick(DialogInterface dialog, int item) {
1036                                                          setFrequency(frequencies[item]);
1037                                                  }
1038                                          });
1039                         AlertDialog alert_freq = builder_freq.create();
1040                         alert_freq.show();
1041                         return true;
1042                 case R.id.select_tracker:
1043                         if (serials != null) {
1044                                 String[] trackers = new String[serials.length+1];
1045                                 trackers[0] = "Auto";
1046                                 for (int i = 0; i < serials.length; i++)
1047                                         trackers[i+1] = String.format("%d", serials[i]);
1048                                 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1049                                 builder_serial.setTitle("Select a tracker");
1050                                 builder_serial.setItems(trackers,
1051                                                         new DialogInterface.OnClickListener() {
1052                                                                 public void onClick(DialogInterface dialog, int item) {
1053                                                                         if (item == 0)
1054                                                                                 select_tracker(0);
1055                                                                         else
1056                                                                                 select_tracker(serials[item-1]);
1057                                                                 }
1058                                                         });
1059                                 AlertDialog alert_serial = builder_serial.create();
1060                                 alert_serial.show();
1061
1062                         }
1063                         return true;
1064                 case R.id.delete_track:
1065                         if (serials != null) {
1066                                 String[] trackers = new String[serials.length];
1067                                 for (int i = 0; i < serials.length; i++)
1068                                         trackers[i] = String.format("%d", serials[i]);
1069                                 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1070                                 builder_serial.setTitle("Delete a track");
1071                                 builder_serial.setItems(trackers,
1072                                                         new DialogInterface.OnClickListener() {
1073                                                                 public void onClick(DialogInterface dialog, int item) {
1074                                                                         delete_track(serials[item]);
1075                                                                 }
1076                                                         });
1077                                 AlertDialog alert_serial = builder_serial.create();
1078                                 alert_serial.show();
1079
1080                         }
1081                         return true;
1082                 case R.id.idle_mode:
1083                         serverIntent = new Intent(this, IdleModeActivity.class);
1084                         serverIntent.putExtra(EXTRA_IDLE_MODE, idle_mode);
1085                         startActivityForResult(serverIntent, REQUEST_IDLE_MODE);
1086                         return true;
1087                 }
1088                 return false;
1089         }
1090
1091         static String direction(AltosGreatCircle from_receiver,
1092                                 Location receiver) {
1093                 if (from_receiver == null)
1094                         return null;
1095
1096                 if (receiver == null)
1097                         return null;
1098
1099                 if (!receiver.hasBearing())
1100                         return null;
1101
1102                 float   bearing = receiver.getBearing();
1103                 float   heading = (float) from_receiver.bearing - bearing;
1104
1105                 while (heading <= -180.0f)
1106                         heading += 360.0f;
1107                 while (heading > 180.0f)
1108                         heading -= 360.0f;
1109
1110                 int iheading = (int) (heading + 0.5f);
1111
1112                 if (-1 < iheading && iheading < 1)
1113                         return "ahead";
1114                 else if (iheading < -179 || 179 < iheading)
1115                         return "backwards";
1116                 else if (iheading < 0)
1117                         return String.format("left %d°", -iheading);
1118                 else
1119                         return String.format("right %d°", iheading);
1120         }
1121
1122         public void onLocationChanged(Location location) {
1123                 this.location = location;
1124                 AltosDebug.debug("Location changed to %f,%f",
1125                                  location.getLatitude(),
1126                                  location.getLongitude());
1127                 update_ui(telemetry_state, state, false);
1128         }
1129
1130         public void onStatusChanged(String provider, int status, Bundle extras) {
1131                 AltosDebug.debug("Location status now %d\n", status);
1132         }
1133
1134         public void onProviderEnabled(String provider) {
1135                 AltosDebug.debug("Location provider enabled %s\n", provider);
1136         }
1137
1138         public void onProviderDisabled(String provider) {
1139                 AltosDebug.debug("Location provider disabled %s\n", provider);
1140         }
1141 }