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