altosdroid: implement tabs interface
[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
22 import android.app.Activity;
23 import android.bluetooth.BluetoothAdapter;
24 import android.bluetooth.BluetoothDevice;
25 import android.content.Intent;
26 import android.content.Context;
27 import android.content.ComponentName;
28 import android.content.ServiceConnection;
29 import android.content.DialogInterface;
30 import android.os.IBinder;
31 import android.os.Bundle;
32 import android.os.Handler;
33 import android.os.Message;
34 import android.os.Messenger;
35 import android.os.RemoteException;
36 import android.support.v4.app.FragmentActivity;
37 import android.support.v4.view.ViewPager;
38 import android.util.Log;
39 import android.view.Menu;
40 import android.view.MenuInflater;
41 import android.view.MenuItem;
42 import android.view.Window;
43 import android.widget.TabHost;
44 import android.widget.TextView;
45 import android.widget.Toast;
46 import android.app.AlertDialog;
47
48 import org.altusmetrum.altoslib_1.*;
49
50 public class AltosDroid extends FragmentActivity {
51         // Debugging
52         private static final String TAG = "AltosDroid";
53         private static final boolean D = true;
54
55         // Message types received by our Handler
56         public static final int MSG_STATE_CHANGE    = 1;
57         public static final int MSG_TELEMETRY       = 2;
58
59         // Intent request codes
60         private static final int REQUEST_CONNECT_DEVICE = 1;
61         private static final int REQUEST_ENABLE_BT      = 2;
62
63         // Layout Views
64         private TextView mTitle;
65
66         // Flight state values
67         private TextView mCallsignView;
68         private TextView mRSSIView;
69         private TextView mSerialView;
70         private TextView mFlightView;
71         private TextView mStateView;
72         private TextView mAgeView;
73
74         // field to display the version at the bottom of the screen
75         private TextView mVersion;
76
77         // Tabs
78         TabHost     mTabHost;
79         ViewPager   mViewPager;
80         TabsAdapter mTabsAdapter;
81
82         // Service
83         private boolean mIsBound   = false;
84         private Messenger mService = null;
85         final Messenger mMessenger = new Messenger(new IncomingHandler(this));
86
87         // Preferences
88         private AltosDroidPreferences prefs = null;
89
90         // TeleBT Config data
91         private AltosConfigData mConfigData = null;
92         // Local Bluetooth adapter
93         private BluetoothAdapter mBluetoothAdapter = null;
94
95         // Text to Speech
96         private AltosVoice mAltosVoice = null;
97
98         // The Handler that gets information back from the Telemetry Service
99         static class IncomingHandler extends Handler {
100                 private final WeakReference<AltosDroid> mAltosDroid;
101                 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
102
103                 @Override
104                 public void handleMessage(Message msg) {
105                         AltosDroid ad = mAltosDroid.get();
106                         switch (msg.what) {
107                         case MSG_STATE_CHANGE:
108                                 if(D) Log.d(TAG, "MSG_STATE_CHANGE: " + msg.arg1);
109                                 switch (msg.arg1) {
110                                 case TelemetryService.STATE_CONNECTED:
111                                         ad.mConfigData = (AltosConfigData) msg.obj;
112                                         String str = String.format(" %s S/N: %d", ad.mConfigData.product, ad.mConfigData.serial);
113                                         ad.mTitle.setText(R.string.title_connected_to);
114                                         ad.mTitle.append(str);
115                                         Toast.makeText(ad.getApplicationContext(), "Connected to " + str, Toast.LENGTH_SHORT).show();
116                                         ad.mAltosVoice.speak("Connected");
117                                         break;
118                                 case TelemetryService.STATE_CONNECTING:
119                                         ad.mTitle.setText(R.string.title_connecting);
120                                         break;
121                                 case TelemetryService.STATE_READY:
122                                 case TelemetryService.STATE_NONE:
123                                         ad.mConfigData = null;
124                                         ad.mTitle.setText(R.string.title_not_connected);
125                                         break;
126                                 }
127                                 break;
128                         case MSG_TELEMETRY:
129                                 ad.update_ui((AltosState) msg.obj);
130                                 break;
131                         }
132                 }
133         };
134
135
136         private ServiceConnection mConnection = new ServiceConnection() {
137                 public void onServiceConnected(ComponentName className, IBinder service) {
138                         mService = new Messenger(service);
139                         try {
140                                 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
141                                 msg.replyTo = mMessenger;
142                                 mService.send(msg);
143                         } catch (RemoteException e) {
144                                 // In this case the service has crashed before we could even do anything with it
145                         }
146                 }
147
148                 public void onServiceDisconnected(ComponentName className) {
149                         // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
150                         mService = null;
151                 }
152         };
153
154         void doBindService() {
155                 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
156                 mIsBound = true;
157         }
158
159         void doUnbindService() {
160                 if (mIsBound) {
161                         // If we have received the service, and hence registered with it, then now is the time to unregister.
162                         if (mService != null) {
163                                 try {
164                                         Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
165                                         msg.replyTo = mMessenger;
166                                         mService.send(msg);
167                                 } catch (RemoteException e) {
168                                         // There is nothing special we need to do if the service has crashed.
169                                 }
170                         }
171                         // Detach our existing connection.
172                         unbindService(mConnection);
173                         mIsBound = false;
174                 }
175         }
176
177         public void registerTab(AltosDroidTab mTab) {
178         }
179
180         public void unregisterTab(AltosDroidTab mTab) {
181         }
182
183         void update_ui(AltosState state) {
184                 mCallsignView.setText(state.data.callsign);
185                 mSerialView.setText(String.format("%d", state.data.serial));
186                 mFlightView.setText(String.format("%d", state.data.flight));
187                 mStateView.setText(state.data.state());
188                 mRSSIView.setText(String.format("%d", state.data.rssi));
189
190                 mAltosVoice.tell(state);
191         }
192
193         static String pos(double p, String pos, String neg) {
194                 String  h = pos;
195                 if (p < 0) {
196                         h = neg;
197                         p = -p;
198                 }
199                 int deg = (int) Math.floor(p);
200                 double min = (p - Math.floor(p)) * 60.0;
201                 return String.format("%d° %9.6f\" %s", deg, min, h);
202         }
203
204         @Override
205         public void onCreate(Bundle savedInstanceState) {
206                 super.onCreate(savedInstanceState);
207                 if(D) Log.e(TAG, "+++ ON CREATE +++");
208
209                 // Get local Bluetooth adapter
210                 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
211
212                 // If the adapter is null, then Bluetooth is not supported
213                 if (mBluetoothAdapter == null) {
214                         Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
215                         finish();
216                         return;
217                 }
218
219                 // Initialise preferences
220                 prefs = new AltosDroidPreferences(this);
221                 AltosPreferences.init(prefs);
222
223                 // Set up the window layout
224                 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
225                 setContentView(R.layout.altosdroid);
226                 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
227
228                 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
229                 mTabHost.setup();
230
231                 mViewPager = (ViewPager)findViewById(R.id.pager);
232                 mViewPager.setOffscreenPageLimit(4);
233
234                 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
235
236                 mTabsAdapter.addTab(mTabHost.newTabSpec("pad").setIndicator("Pad"), TabPad.class, null);
237                 mTabsAdapter.addTab(mTabHost.newTabSpec("ascent").setIndicator("Ascent"), TabAscent.class, null);
238                 mTabsAdapter.addTab(mTabHost.newTabSpec("descent").setIndicator("Descent"), TabDescent.class, null);
239                 mTabsAdapter.addTab(mTabHost.newTabSpec("landed").setIndicator("Landed"), TabLanded.class, null);
240                 mTabsAdapter.addTab(mTabHost.newTabSpec("map").setIndicator("Map"), TabMap.class, null);
241
242
243                 // Set up the custom title
244                 mTitle = (TextView) findViewById(R.id.title_left_text);
245                 mTitle.setText(R.string.app_name);
246                 mTitle = (TextView) findViewById(R.id.title_right_text);
247
248                 // Display the Version
249                 mVersion = (TextView) findViewById(R.id.version);
250                 mVersion.setText("Version: " + BuildInfo.version +
251                                  "  Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
252                                  "  (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
253
254                 mCallsignView  = (TextView) findViewById(R.id.callsign_value);
255                 mRSSIView      = (TextView) findViewById(R.id.rssi_value);
256                 mSerialView    = (TextView) findViewById(R.id.serial_value);
257                 mFlightView    = (TextView) findViewById(R.id.flight_value);
258                 mStateView     = (TextView) findViewById(R.id.state_value);
259                 mAgeView       = (TextView) findViewById(R.id.age_value);
260
261                 mAltosVoice = new AltosVoice(this);
262         }
263
264         @Override
265         public void onStart() {
266                 super.onStart();
267                 if(D) Log.e(TAG, "++ ON START ++");
268
269                 if (!mBluetoothAdapter.isEnabled()) {
270                         Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
271                         startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
272                 }
273
274                 // Start Telemetry Service
275                 startService(new Intent(AltosDroid.this, TelemetryService.class));
276
277                 doBindService();
278         }
279
280         @Override
281         public synchronized void onResume() {
282                 super.onResume();
283                 if(D) Log.e(TAG, "+ ON RESUME +");
284         }
285
286         @Override
287         public synchronized void onPause() {
288                 super.onPause();
289                 if(D) Log.e(TAG, "- ON PAUSE -");
290         }
291
292         @Override
293         public void onStop() {
294                 super.onStop();
295                 if(D) Log.e(TAG, "-- ON STOP --");
296
297                 doUnbindService();
298         }
299
300         @Override
301         public void onDestroy() {
302                 super.onDestroy();
303                 if(D) Log.e(TAG, "--- ON DESTROY ---");
304
305                 mAltosVoice.stop();
306         }
307
308         public void onActivityResult(int requestCode, int resultCode, Intent data) {
309                 if(D) Log.d(TAG, "onActivityResult " + resultCode);
310                 switch (requestCode) {
311                 case REQUEST_CONNECT_DEVICE:
312                         // When DeviceListActivity returns with a device to connect to
313                         if (resultCode == Activity.RESULT_OK) {
314                                 connectDevice(data);
315                         }
316                         break;
317                 case REQUEST_ENABLE_BT:
318                         // When the request to enable Bluetooth returns
319                         if (resultCode == Activity.RESULT_OK) {
320                                 // Bluetooth is now enabled, so set up a chat session
321                                 //setupChat();
322                         } else {
323                                 // User did not enable Bluetooth or an error occured
324                                 Log.e(TAG, "BT not enabled");
325                                 stopService(new Intent(AltosDroid.this, TelemetryService.class));
326                                 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
327                                 finish();
328                         }
329                         break;
330                 }
331         }
332
333         private void connectDevice(Intent data) {
334                 // Get the device MAC address
335                 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
336                 // Get the BLuetoothDevice object
337                 BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
338                 // Attempt to connect to the device
339                 try {
340                         if (D) Log.d(TAG, "Connecting to " + device.getName());
341                         mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, device));
342                 } catch (RemoteException e) {
343                 }
344         }
345
346         @Override
347         public boolean onCreateOptionsMenu(Menu menu) {
348                 MenuInflater inflater = getMenuInflater();
349                 inflater.inflate(R.menu.option_menu, menu);
350                 return true;
351         }
352
353         void setFrequency(double freq) {
354                 try {
355                         mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
356                 } catch (RemoteException e) {
357                 }
358         }
359
360         void setFrequency(String freq) {
361                 try {
362                         setFrequency (Double.parseDouble(freq.substring(11, 17)));
363                 } catch (NumberFormatException e) {
364                 }
365         }
366
367         @Override
368         public boolean onOptionsItemSelected(MenuItem item) {
369                 Intent serverIntent = null;
370                 switch (item.getItemId()) {
371                 case R.id.connect_scan:
372                         // Launch the DeviceListActivity to see devices and do scan
373                         serverIntent = new Intent(this, DeviceListActivity.class);
374                         startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
375                         return true;
376                 case R.id.select_freq:
377                         // Set the TBT radio frequency
378
379                         final String[] frequencies = {
380                                 "Channel 0 (434.550MHz)",
381                                 "Channel 1 (434.650MHz)",
382                                 "Channel 2 (434.750MHz)",
383                                 "Channel 3 (434.850MHz)",
384                                 "Channel 4 (434.950MHz)",
385                                 "Channel 5 (435.050MHz)",
386                                 "Channel 6 (435.150MHz)",
387                                 "Channel 7 (435.250MHz)",
388                                 "Channel 8 (435.350MHz)",
389                                 "Channel 9 (435.450MHz)"
390                         };
391
392                         AlertDialog.Builder builder = new AlertDialog.Builder(this);
393                         builder.setTitle("Pick a frequency");
394                         builder.setItems(frequencies,
395                                          new DialogInterface.OnClickListener() {
396                                                  public void onClick(DialogInterface dialog, int item) {
397                                                          setFrequency(frequencies[item]);
398                                                  }
399                                          });
400                         AlertDialog alert = builder.create();
401                         alert.show();
402                         return true;
403                 }
404                 return false;
405         }
406
407 }