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