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