1
/* ***** BEGIN LICENSE BLOCK *****
2
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
4
* The contents of this file are subject to the Mozilla Public License Version
5
* 1.1 (the "License"); you may not use this file except in compliance with
6
* the License. You may obtain a copy of the License at
7
* http://www.mozilla.org/MPL/
9
* Software distributed under the License is distributed on an "AS IS" basis,
10
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
11
* for the specific language governing rights and limitations under the
14
* The Original Code is Android SUTAgent code.
16
* The Initial Developer of the Original Code is
18
* Portions created by the Initial Developer are Copyright (C) 2010
19
* the Initial Developer. All Rights Reserved.
22
* Bob Moss <bmoss@mozilla.com>
24
* Alternatively, the contents of this file may be used under the terms of
25
* either the GNU General Public License Version 2 or later (the "GPL"), or
26
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
27
* in which case the provisions of the GPL or the LGPL are applicable instead
28
* of those above. If you wish to allow use of your version of this file only
29
* under the terms of either the GPL or the LGPL, and not to allow others to
30
* use your version of this file under the terms of the MPL, indicate your
31
* decision by deleting the provisions above and replace them with the notice
32
* and other provisions required by the GPL or the LGPL. If you do not delete
33
* the provisions above, a recipient may use your version of this file under
34
* the terms of any one of the MPL, the GPL or the LGPL.
36
* ***** END LICENSE BLOCK ***** */
38
package com.mozilla.SUTAgentAndroid;
41
import java.io.PrintWriter;
42
import java.net.InetAddress;
43
import java.net.NetworkInterface;
44
import java.net.SocketException;
45
import java.util.Enumeration;
46
import java.util.List;
47
import java.util.Timer;
48
import com.mozilla.SUTAgentAndroid.service.ASMozStub;
49
import com.mozilla.SUTAgentAndroid.service.DoCommand;
51
// import dalvik.system.VMRuntime;
52
import android.app.Activity;
53
import android.app.KeyguardManager;
54
import android.bluetooth.BluetoothAdapter;
55
import android.content.BroadcastReceiver;
56
// import android.content.ComponentName;
57
import android.content.Context;
58
import android.content.Intent;
59
import android.content.IntentFilter;
60
import android.net.Uri;
61
import android.net.wifi.SupplicantState;
62
import android.net.wifi.WifiConfiguration;
63
import android.net.wifi.WifiInfo;
64
import android.net.wifi.WifiManager;
65
import android.net.wifi.WifiManager.WifiLock;
66
import android.os.BatteryManager;
67
import android.os.Bundle;
68
import android.os.Debug;
69
import android.os.PowerManager;
70
import android.telephony.TelephonyManager;
71
import android.util.Log;
72
import android.view.Menu;
73
import android.view.MenuItem;
74
import android.view.View;
75
import android.view.View.OnClickListener;
76
import android.widget.Button;
77
import android.widget.TextView;
78
import android.widget.Toast;
80
public class SUTAgentAndroid extends Activity
82
public static final int START_PRG = 1959;
83
MenuItem mExitMenuItem;
86
// public static SUTAgentAndroid me = null;
87
public static String sUniqueID = null;
88
public static String sLocalIPAddr = null;
89
public static String sACStatus = null;
90
public static String sPowerStatus = null;
91
public static int nChargeLevel = 0;
92
public static int nBatteryTemp = 0;
94
String lineSep = System.getProperty("line.separator");
95
public PrintWriter dataOut = null;
97
private static boolean bNetworkingStarted = false;
98
private static String RegSvrIPAddr = "";
99
private static String RegSvrIPPort = "";
100
private static String HardwareID = "";
101
private static String Pool = "";
102
private static String sRegString = "";
104
private WifiLock wl = null;
105
private PowerManager.WakeLock pwl = null;
107
private BroadcastReceiver battReceiver = null;
108
// private ComponentName service = null;
110
public boolean onCreateOptionsMenu(Menu menu)
112
mExitMenuItem = menu.add("Exit");
113
mExitMenuItem.setIcon(android.R.drawable.ic_menu_close_clear_cancel);
114
return super.onCreateOptionsMenu(menu);
117
public boolean onMenuItemSelected(int featureId, MenuItem item)
119
if (item == mExitMenuItem)
123
return super.onMenuItemSelected(featureId, item);
126
public static String getRegSvrIPAddr()
128
return(RegSvrIPAddr);
131
/** Called when the activity is first created. */
133
public void onCreate(Bundle savedInstanceState)
135
super.onCreate(savedInstanceState);
136
setContentView(R.layout.main);
138
// Debug.waitForDebugger();
140
// long lHeapSize = VMRuntime.getRuntime().getMinimumHeapSize();
141
// lHeapSize = 16000000;
142
// VMRuntime.getRuntime().setMinimumHeapSize(lHeapSize);
144
// Keep phone from locking or remove lock on screen
145
KeyguardManager km = (KeyguardManager)getSystemService(Context.KEYGUARD_SERVICE);
148
KeyguardManager.KeyguardLock kl = km.newKeyguardLock("SUTAgent");
150
kl.disableKeyguard();
153
// No sleeping on the job
154
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
157
pwl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "SUTAgent");
162
DoCommand dc = new DoCommand(getApplication());
164
// Get configuration settings from "ini" file
165
File dir = getFilesDir();
166
File iniFile = new File(dir, "SUTAgent.ini");
167
String sIniFile = iniFile.getAbsolutePath();
169
SUTAgentAndroid.RegSvrIPAddr = dc.GetIniData("Registration Server", "IPAddr", sIniFile);
170
SUTAgentAndroid.RegSvrIPPort = dc.GetIniData("Registration Server", "PORT", sIniFile);
171
SUTAgentAndroid.HardwareID = dc.GetIniData("Registration Server", "HARDWARE", sIniFile);
172
SUTAgentAndroid.Pool = dc.GetIniData("Registration Server", "POOL", sIniFile);
174
TextView tv = (TextView) this.findViewById(R.id.Textview01);
176
if (getLocalIpAddress() == null)
177
setUpNetwork(sIniFile);
182
WifiManager wifiMan = (WifiManager)getSystemService(Context.WIFI_SERVICE);
183
String macAddress = "Unknown";
186
wifi = wifiMan.getConnectionInfo();
189
macAddress = wifi.getMacAddress();
190
if (macAddress != null)
191
sUniqueID = macAddress;
195
if (sUniqueID == null)
197
BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
198
if (ba.isEnabled() != true)
201
while(ba.getState() != BluetoothAdapter.STATE_ON)
206
catch (InterruptedException e)
212
sUniqueID = ba.getAddress();
215
while(ba.getState() != BluetoothAdapter.STATE_OFF)
220
catch (InterruptedException e)
228
sUniqueID = ba.getAddress();
229
sUniqueID.toLowerCase();
233
if (sUniqueID == null)
235
TelephonyManager mTelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
236
if (mTelephonyMgr != null)
238
sUniqueID = mTelephonyMgr.getDeviceId();
239
if (sUniqueID == null)
241
sUniqueID = "0011223344556677";
246
sLocalIPAddr = getLocalIpAddress();
247
Toast.makeText(getApplication().getApplicationContext(), "SUTAgent [" + sLocalIPAddr + "] ...", Toast.LENGTH_LONG).show();
249
String sConfig = "Unique ID: " + sUniqueID + lineSep;
250
sConfig += "OS Info" + lineSep;
251
sConfig += "\t" + dc.GetOSInfo() + lineSep;
252
sConfig += "Screen Info" + lineSep;
253
int [] xy = dc.GetScreenXY();
254
sConfig += "\t Width: " + xy[0] + lineSep;
255
sConfig += "\t Height: " + xy[1] + lineSep;
256
sConfig += "Memory Info" + lineSep;
257
sConfig += "\t" + dc.GetMemoryInfo() + lineSep;
258
sConfig += "Network Info" + lineSep;
259
sConfig += "\tMac Address: " + macAddress + lineSep;
260
sConfig += "\tIP Address: " + sLocalIPAddr + lineSep;
262
sRegString = "NAME=" + sUniqueID;
263
sRegString += "&IPADDR=" + sLocalIPAddr;
264
sRegString += "&CMDPORT=" + 20701;
265
sRegString += "&DATAPORT=" + 20700;
266
sRegString += "&OS=Android-" + dc.GetOSInfo();
267
sRegString += "&SCRNWIDTH=" + xy[0];
268
sRegString += "&SCRNHEIGHT=" + xy[1];
269
sRegString += "&BPP=8";
270
sRegString += "&MEMORY=" + dc.GetMemoryConfig();
271
sRegString += "&HARDWARE=" + HardwareID;
272
sRegString += "&POOL=" + Pool;
274
String sTemp = Uri.encode(sRegString,"=&");
275
sRegString = "register " + sTemp;
277
if (!bNetworkingStarted)
279
Thread thread = new Thread(null, doStartService, "StartServiceBkgnd");
281
// ToDoListening(1,300,dc);
282
bNetworkingStarted = true;
284
if (RegSvrIPAddr.length() > 0)
286
sRegRet = dc.RegisterTheDevice(RegSvrIPAddr, RegSvrIPPort, sRegString);
287
if (sRegRet.contains("ok"))
289
sConfig += "Registered with testserver" + lineSep;
290
sConfig += "\tIPAddress: " + RegSvrIPAddr + lineSep;
291
if (RegSvrIPPort.length() > 0)
292
sConfig += "\tPort: " + RegSvrIPPort + lineSep;
295
sConfig += "Not registered with testserver" + lineSep;
298
sConfig += "Not registered with testserver" + lineSep;
303
monitorBatteryState();
305
final Button goButton = (Button) findViewById(R.id.Button01);
306
goButton.setOnClickListener(new OnClickListener() {
307
public void onClick(View v) {
313
protected void onActivityResult(int requestCode, int resultCode, Intent data)
315
if (requestCode == START_PRG)
317
Toast.makeText(getApplication().getApplicationContext(), "SUTAgent startprg finished ...", Toast.LENGTH_LONG).show();
322
public void onDestroy()
327
Intent listenerSvc = new Intent(this, ASMozStub.class);
328
listenerSvc.setAction("com.mozilla.SUTAgentAndroid.service.LISTENER_SERVICE");
329
stopService(listenerSvc);
330
bNetworkingStarted = false;
332
unregisterReceiver(battReceiver);
333
KeyguardManager km = (KeyguardManager)getSystemService(Context.KEYGUARD_SERVICE);
336
KeyguardManager.KeyguardLock kl = km.newKeyguardLock("SUTAgent");
338
kl.reenableKeyguard();
349
private void monitorBatteryState()
351
battReceiver = new BroadcastReceiver()
353
public void onReceive(Context context, Intent intent)
355
StringBuilder sb = new StringBuilder();
357
int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); // charge level from 0 to scale inclusive
358
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); // Max value for charge level
359
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
360
int health = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, -1);
361
boolean present = intent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, false);
362
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1); //0 if the device is not plugged in; 1 if plugged into an AC power adapter; 2 if plugged in via USB.
363
// int voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1); // voltage in millivolts
364
nBatteryTemp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1); // current battery temperature in tenths of a degree Centigrade
365
// String technology = intent.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY);
367
nChargeLevel = -1; // percentage, or -1 for unknown
368
if (rawlevel >= 0 && scale > 0)
370
nChargeLevel = (rawlevel * 100) / scale;
374
sACStatus = "ONLINE";
376
sACStatus = "OFFLINE";
378
if (present == false)
379
sb.append("NO BATTERY");
382
if (nChargeLevel < 10)
383
sb.append("Critical");
384
else if (nChargeLevel < 33)
386
else if (nChargeLevel > 80)
390
if (BatteryManager.BATTERY_HEALTH_OVERHEAT == health)
392
sb.append("Overheated ");
393
sb.append((((float)(nBatteryTemp))/10));
400
case BatteryManager.BATTERY_STATUS_UNKNOWN:
401
// old emulator; maybe also when plugged in with no battery
403
sb.append(" UNKNOWN");
405
case BatteryManager.BATTERY_STATUS_CHARGING:
406
sb.append(" CHARGING");
408
case BatteryManager.BATTERY_STATUS_DISCHARGING:
409
sb.append(" DISCHARGING");
411
case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
412
sb.append(" NOTCHARGING");
414
case BatteryManager.BATTERY_STATUS_FULL:
419
sb.append("Unknown");
424
sPowerStatus = sb.toString();
428
IntentFilter battFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
429
registerReceiver(battReceiver, battFilter);
432
public boolean setUpNetwork(String sIniFile)
434
boolean bRet = false;
437
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
438
WifiConfiguration wc = new WifiConfiguration();
439
DoCommand tmpdc = new DoCommand(getApplication());
441
String ssid = tmpdc.GetIniData("Network Settings", "SSID", sIniFile);
442
String auth = tmpdc.GetIniData("Network Settings", "AUTH", sIniFile);
443
String encr = tmpdc.GetIniData("Network Settings", "ENCR", sIniFile);
444
String key = tmpdc.GetIniData("Network Settings", "KEY", sIniFile);
445
String eap = tmpdc.GetIniData("Network Settings", "EAP", sIniFile);
446
String adhoc = tmpdc.GetIniData("Network Settings", "ADHOC", sIniFile);
448
Toast.makeText(getApplication().getApplicationContext(), "Starting and configuring network", Toast.LENGTH_LONG).show();
450
ContentResolver cr = getContentResolver();
453
nRet = Settings.System.getInt(cr, Settings.System.WIFI_USE_STATIC_IP);
454
String foo2 = "" + nRet;
455
} catch (SettingNotFoundException e1) {
456
// TODO Auto-generated catch block
457
e1.printStackTrace();
461
wc.SSID = "\"Mozilla-Build\"";
462
wc.preSharedKey = "\"MozillaBuildQA500\"";
463
wc.hiddenSSID = true;
464
wc.status = WifiConfiguration.Status.ENABLED;
465
wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
466
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
467
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
468
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
469
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
470
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
471
wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
473
wc.SSID = "\"" + ssid + "\"";
474
// wc.SSID = "\"Mozilla-G\"";
475
// wc.SSID = "\"Mozilla\"";
477
if (auth.contentEquals("wpa2"))
479
wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
480
wc.preSharedKey = null;
483
if (encr.contentEquals("aes"))
485
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
486
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
489
if (eap.contentEquals("peap"))
491
wc.eap.setValue("PEAP");
492
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
493
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
496
wc.hiddenSSID = false;
497
wc.status = WifiConfiguration.Status.ENABLED;
499
wc.password.setValue("\"password\"");
500
wc.identity.setValue("\"bmoss@mozilla.com\"");
502
if (!wifi.isWifiEnabled())
503
wifi.setWifiEnabled(true);
505
while(wifi.getWifiState() != WifiManager.WIFI_STATE_ENABLED)
512
wl = wifi.createWifiLock(WifiManager.WIFI_MODE_FULL, "SUTAgent");
516
WifiConfiguration foo = null;
519
List<WifiConfiguration> connsLst = wifi.getConfiguredNetworks();
520
int nConns = connsLst.size();
521
for (int i = 0; i < nConns; i++)
524
foo = connsLst.get(i);
525
if (foo.SSID.equalsIgnoreCase(wc.SSID))
527
nNetworkID = foo.networkId;
528
wc.networkId = foo.networkId;
535
if (nNetworkID != -1)
537
res = wifi.updateNetwork(wc);
541
res = wifi.addNetwork(wc);
544
Log.d("WifiPreference", "add Network returned " + res );
546
boolean b = wifi.enableNetwork(res, true);
547
Log.d("WifiPreference", "enableNetwork returned " + b );
549
wifi.saveConfiguration();
551
WifiInfo wi = wifi.getConnectionInfo();
552
SupplicantState ss = wi.getSupplicantState();
557
while (ss.compareTo(SupplicantState.COMPLETED) != 0)
562
catch (InterruptedException e)
571
wi = wifi.getConnectionInfo();
572
ss = wi.getSupplicantState();
577
Toast.makeText(getApplication().getApplicationContext(), "Unable to start and configure network", Toast.LENGTH_LONG).show();
582
Toast.makeText(getApplication().getApplicationContext(), "Resetting wifi interface", Toast.LENGTH_LONG).show();
585
wifi.setWifiEnabled(false);
586
while(wifi.getWifiState() != WifiManager.WIFI_STATE_DISABLED)
591
wifi.setWifiEnabled(true);
592
while(wifi.getWifiState() != WifiManager.WIFI_STATE_ENABLED)
596
b = wifi.enableNetwork(res, true);
597
Log.d("WifiPreference", "enableNetwork returned " + b );
606
while(getLocalIpAddress() == null)
612
Toast.makeText(getApplication().getApplicationContext(), "Network started and configured", Toast.LENGTH_LONG).show();
618
private Runnable doStartService = new Runnable()
622
Intent listenerService = new Intent();
623
listenerService.setAction("com.mozilla.SUTAgentAndroid.service.LISTENER_SERVICE");
624
startService(listenerService);
625
// service = startService(listenerService);
629
class ToDoListener extends TimerTask
631
boolean bFirstRun = true;
636
ToDoListener(DoCommand dc)
643
if (bFirstRun == true)
645
Intent listenerService = new Intent();
646
listenerService.setAction("com.mozilla.SUTAgentAndroid.service.LISTENER_SERVICE");
647
service = startService(listenerService);
654
String sRet = this.dc.SendPing("www.mozilla.org", null);
655
if (sRet.contains("3 received"))
658
this.dc.StartAlert();
666
public void ToDoListening(int delay, int interval, DoCommand dc)
670
// timer.scheduleAtFixedRate(new ToDoListener(dc), delay * 1000, interval * 1000);
671
// timer.schedule(new ToDoListener(dc), delay * 1000);
672
timer.schedule(new ToDoListener(), delay * 1000);
675
class DoHeartBeat extends TimerTask
679
DoHeartBeat(PrintWriter out)
688
Calendar cal = Calendar.getInstance();
689
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HH:mm:ss");
690
sRet = sdf.format(cal.getTime());
691
sRet += " Thump thump - " + sUniqueID + "\r\n";
698
public void StartHeartBeat(PrintWriter out)
700
// start the heartbeat
704
timer.scheduleAtFixedRate(new DoHeartBeat(dataOut), 0, 60000);
707
public void StopHeartBeat()
709
// stop the heartbeat
721
public String getLocalIpAddress()
725
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)
727
NetworkInterface intf = en.nextElement();
728
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
730
InetAddress inetAddress = enumIpAddr.nextElement();
731
if (!inetAddress.isLoopbackAddress())
733
return inetAddress.getHostAddress().toString();
738
catch (SocketException ex)
740
Toast.makeText(getApplication().getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show();
b'\\ No newline at end of file'