Skip to content

Commit

Permalink
Restructured the logging process
Browse files Browse the repository at this point in the history
  • Loading branch information
reugene committed Jun 21, 2012
1 parent 04a2fdb commit dce5490
Show file tree
Hide file tree
Showing 9 changed files with 152 additions and 450 deletions.
5 changes: 5 additions & 0 deletions .gitignore
@@ -1 +1,6 @@
*.DS_Store
.classpath
.project
.settings/
bin/
gen/
2 changes: 1 addition & 1 deletion res/xml/preferences.xml
Expand Up @@ -55,7 +55,7 @@

<PreferenceCategory android:title="Debug">
<Preference android:title="Clear Messages" android:summary="Clears all messages in our local database" android:key="clear_messages"/>
<Preference android:title="Send Debug Log" android:summary="Send a debug log to Nyaruka" android:key="send_log"/>
<Preference android:title="Send Debug Log" android:summary="Send a debug log to Admin" android:key="send_log"/>
</PreferenceCategory>

</PreferenceScreen>
Expand Up @@ -149,7 +149,6 @@ public boolean isActionViewExpanded() {
return false;
}

@Override
public MenuItem setOnActionExpandListener(OnActionExpandListener onActionExpandListener) {
// Noop
return this;
Expand Down
136 changes: 78 additions & 58 deletions src/com/nyaruka/androidrelay/CheckService.java
Expand Up @@ -15,6 +15,7 @@

import com.commonsware.cwac.wakeful.WakefulIntentService;
import com.nyaruka.androidrelay.AndroidRelay.PhoneState;
import com.nyaruka.log.LogCollector;

public class CheckService extends WakefulIntentService {
public static final String TAG = AndroidRelay.TAG;
Expand Down Expand Up @@ -87,10 +88,29 @@ public void tickleAirplaneMode(){
Thread.sleep(30000);
} catch (Throwable t){}
}

/**
* Restores our WIFI/DATA state to whatever is in our preference file. No-op if
* our current state is the same as our preferred state.
*/
public void restoreDefaultNetwork(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

boolean isWifiPreferred = (prefs.getString("pref_net", "0").equals("0"));
WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

if (wifi.isWifiEnabled() != isWifiPreferred){
// toggle back to the preferred network
wifi.setWifiEnabled(isWifiPreferred);

try{
Thread.sleep(30000);
} catch (Throwable t){}
}
}

@Override
protected void doWakefulWork(Intent intent) {

Log.d(TAG, "==Check service running");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

Expand All @@ -103,27 +123,13 @@ protected void doWakefulWork(Intent intent) {

// grab the relayer service, seeing if it started
RelayService relayer = RelayService.get();


if (relayer == null){
Log.d(TAG, "No RelayService started yet, awaiting.");
return;
}

Log.d(TAG, "Which Network is Prefered " + prefs.getString("pref_net", "0"));
boolean isWifiPreferred = (prefs.getString("pref_net", "0").equals("0"));
WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

if(isWifiPreferred) {
Log.d(TAG, "__ Preferred network before airplane mode: WIFI");
}else{
Log.d(TAG, "__ Preferred network before airplane mode: MOBILE DATA");
}

// toggle back to the preferred network
wifi.setWifiEnabled(isWifiPreferred);

if (RelayService.isReset){
if (RelayService.doReset){
Log.d(TAG, "__RESTING PROCESS");
try{
Log.d(TAG, "__REST - tickling airplane mode");
Expand All @@ -133,21 +139,12 @@ protected void doWakefulWork(Intent intent) {
Log.d(TAG, "__REST - done tickling default APN mode");

// disable the reset message
RelayService.isReset = false;
RelayService.doReset = false;
} catch (Throwable t){
Log.d(TAG, "Error thrown checking network connectivity", t);
}
}

// toggle back to the preferred network
wifi.setWifiEnabled(isWifiPreferred);

if(isWifiPreferred) {
Log.d(TAG, "__ Preferred network after airplane mode: WIFI");
}else{
Log.d(TAG, "__ Preferred network after airplane mode: MOBILE DATA");
}

// check our power levels
try{
relayer.checkPowerStatus();
Expand All @@ -161,6 +158,29 @@ protected void doWakefulWork(Intent intent) {
} catch (Throwable t){
Log.d(TAG, "Error running check service.", t);
}

// are we meant to send a log? do so
if (RelayService.doSendLog){
String log = LogCollector.collectLog();

if (log != null){
if (RelayService.sendAlert(getApplicationContext(), "Relay Log", log)){
RelayService.doSendLog = false;
} else {
relayer.toggleConnection();
if (RelayService.sendAlert(getApplicationContext(), "Relay Log", log)){
RelayService.doSendLog = false;
} else {
Log.d(TAG, "Failed sending log after two attempts, will retry on next check");
}
}
} else {
Log.d(TAG, "Failed collecting log, will retry on next check");
}
}

// reset our connect if needbe
restoreDefaultNetwork();

// reschedule ourselves
schedule(this.getApplicationContext());
Expand All @@ -170,7 +190,7 @@ protected void doCheckWork(RelayService relayer){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean process_incoming = prefs.getBoolean("process_incoming", false);
boolean process_outgoing = prefs.getBoolean("process_outgoing", false);

if (process_outgoing){
try{
relayer.resendErroredSMS();
Expand All @@ -179,6 +199,9 @@ protected void doCheckWork(RelayService relayer){
}
}

// set our network to our default
restoreDefaultNetwork();

if (process_incoming){
try{
Log.d(TAG, "__ SENDING PENDING MESSAGES");
Expand All @@ -190,7 +213,7 @@ protected void doCheckWork(RelayService relayer){
relayer.sendPendingMessagesToServer();
} catch (IOException e1){
Log.d(TAG, "__ FAILED TO SEND PENDING MESSAGES, SET RESET LABEL TO true");
RelayService.isReset = true;
RelayService.doReset = true;
} catch (Throwable tt){
Log.d(TAG, "Error sending messages to server", e);
}
Expand All @@ -200,50 +223,44 @@ protected void doCheckWork(RelayService relayer){
}

if (process_outgoing) {
// set our network to our default
restoreDefaultNetwork();

try{
Log.d(TAG, "__ MARKING DELIVERIES");
relayer.markDeliveriesOnServer();
} catch (IOException e){
if (!relayer.isConnectionToggled()){
try{
Log.d(TAG, "Error marking deliveries on the server, toggling connection", e);
relayer.toggleConnection();
relayer.sendPendingMessagesToServer();
} catch (IOException e1) {
Log.d(TAG, "__ FAILED TO SEND PENDING MESSAGES, SET RESET LABEL TO true");
RelayService.isReset = true;
} catch (Throwable tt){
Log.d(TAG, "Error marking deliveries on the server", e);
}
} else {
try{
Log.d(TAG, "Error marking deliveries on the server, toggling connection", e);
relayer.toggleConnection();
relayer.markDeliveriesOnServer();
} catch (IOException e1) {
Log.d(TAG, "__ FAILED TO MARK DELIVERIES, SET RESET LABEL TO true");
RelayService.doReset = true;
} catch (Throwable tt){
Log.d(TAG, "Error marking deliveries on the server", e);
Log.d(TAG, "__ FAILED TO SEND PENDING MESSAGES, SET RESET LABEL TO true");
RelayService.isReset = true;
}
}
} catch (Throwable t){
Log.d(TAG, "Error marking deliveries on the server", t);
}

// set our network to our default
restoreDefaultNetwork();

try{
Log.d(TAG, "__ CHECKING OUTBOX");
relayer.checkOutbox();
} catch (IOException e){
if (!relayer.isConnectionToggled()){
try{
Log.d(TAG, "Error checking outbox, toggling connection", e);
relayer.toggleConnection();
relayer.sendPendingMessagesToServer();
} catch (Exception e1) {
Log.d(TAG, "__ FAILED TO SEND PENDING MESSAGES TO SERVER, SET RESET LABEL TO: 'true'");
RelayService.isReset = true;
} catch (Throwable tt){
Log.d(TAG, "Error checking outbox", e);
}
} else {
try{
Log.d(TAG, "Error checking outbox, toggling connection", e);
relayer.toggleConnection();
relayer.checkOutbox();
} catch (Exception e1) {
Log.d(TAG, "__ FAILED TO CHECK OUTBOX, SET RESET LABEL TO: 'true'");
RelayService.doReset = true;
} catch (Throwable tt){
Log.d(TAG, "Error checking outbox", e);
Log.d(TAG, "__ FAILED TO SEND PENDING MESSAGES TO SERVER, SET RESET LABEL TO: 'true'");
RelayService.isReset = true;
}
}
} catch (Throwable t){
Log.d(TAG, "Error checking outbox", t);
}
Expand All @@ -254,6 +271,9 @@ protected void doCheckWork(RelayService relayer){
} catch (Throwable t){
Log.d(TAG, "Error trimming message", t);
}

// set our network to our default
restoreDefaultNetwork();
}

public static void schedule(Context context){
Expand Down
1 change: 0 additions & 1 deletion src/com/nyaruka/androidrelay/MainActivity.java
Expand Up @@ -50,7 +50,6 @@ public static void clearMessages(){
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ( keyCode == KeyEvent.KEYCODE_MENU ) {
Log.d(TAG, "MENU pressed");
Intent settingsActivity = new Intent(getBaseContext(), SettingsActivity.class);
startActivity(settingsActivity);
return true;
Expand Down
53 changes: 10 additions & 43 deletions src/com/nyaruka/androidrelay/RelayService.java
Expand Up @@ -23,7 +23,6 @@
import com.commonsware.cwac.wakeful.WakefulIntentService;
import com.nyaruka.androidrelay.data.TextMessage;
import com.nyaruka.androidrelay.data.TextMessageHelper;
import com.nyaruka.log.SendLogActivity;

import android.app.Service;
import android.content.ContentResolver;
Expand Down Expand Up @@ -65,7 +64,8 @@ public class RelayService extends Service implements SMSModem.SmsModemListener {
public static final Uri APN_TABLE_URI = Uri.parse("content://telephony/carriers");
public static final Uri PREFERRED_APN_URI = Uri.parse("content://telephony/carriers/preferapn");

public static boolean isReset = false;
public static boolean doReset = false;
public static boolean doSendLog = false;

public int createAPN(String name, String apnAddr) {
int id = -1;
Expand Down Expand Up @@ -257,7 +257,7 @@ else if (s_lastAlert != ALERT_POWER_ON){
*/
public static boolean sendAlert(Context context, String subject, String body){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String hostname = prefs.getString("rapidsms_hostname", null);
String hostname = prefs.getString("router_hostname", null);

Log.d(TAG, "__SENDING ALERT: " + subject);

Expand All @@ -271,10 +271,10 @@ public static boolean sendAlert(Context context, String subject, String body){
StringBuilder conf = new StringBuilder();
conf.append("SMS Relay Version: " + AndroidRelay.getVersionNumber(context));
conf.append("\n");
conf.append("\nHostname: " + prefs.getString("rapidsms_hostname", null));
String backend = prefs.getString("rapidsms_backend", null);
conf.append("\nHostname: " + prefs.getString("router_hostname", null));
String backend = prefs.getString("router_backend", null);
conf.append("\nBackend:" + backend);
conf.append("\nPassword:" + prefs.getString("rapidsms_password", null));
conf.append("\nPassword:" + prefs.getString("router_password", null));
conf.append("\n");
conf.append("\nProcess Incoming:" + prefs.getBoolean("process_incoming", false));
conf.append("\nProcess Outgoing:" + prefs.getBoolean("process_outgoing", false));
Expand Down Expand Up @@ -304,7 +304,7 @@ public static boolean sendAlert(Context context, String subject, String body){
try{
HttpPost post = new HttpPost("http://" + hostname + "/router/alert");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("password", "" + prefs.getString("rapidsms_password", null)));
nameValuePairs.add(new BasicNameValuePair("password", "" + prefs.getString("router_password", null)));
nameValuePairs.add(new BasicNameValuePair("subject", "[" + backend + "] " + subject));
nameValuePairs.add(new BasicNameValuePair("body", body));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Expand All @@ -329,9 +329,6 @@ public static boolean sendAlert(Context context, String subject, String body){
*/
public void toggleConnection(){
WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
m_targetWifiState = UNCHANGED;

m_targetWifiState = wifi.isWifiEnabled() ? ON : OFF;

// well that didn't work, let's flip our connection status, that might just help.. we sleep a bit so things can connect
boolean newWifiState = !wifi.isWifiEnabled();
Expand All @@ -343,26 +340,6 @@ public void toggleConnection(){
Thread.sleep(30000);
} catch (Throwable tt){}
}

public boolean isConnectionToggled(){
return m_targetWifiState != UNCHANGED;
}

/**
* Restores the previous connection settings. That is if we were on WiFi previously, then this
* method will reenable WiFi again.
*/
public void restoreConnection(){
WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (m_targetWifiState == OFF){
Log.d(TAG, "Restoring WIFI to Off");
wifi.setWifiEnabled(false);
} else if (m_targetWifiState == ON){
Log.d(TAG, "Restoring WIFI to On");
wifi.setWifiEnabled(true);
}
m_targetWifiState = UNCHANGED;
}

/***
* This should be run only when our service starts, and takes care of resending any messages
Expand Down Expand Up @@ -687,10 +664,7 @@ public void onNewSMS(String number, String message) {

// if someone sends 'keyword log' then send a log to the server
if (message.equalsIgnoreCase(keyword + " log")){
final Intent intent = new Intent(SendLogActivity.ACTION_SEND_LOG);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(SendLogActivity.EXTRA_SEND_INTENT_ACTION, Intent.ACTION_SENDTO);
startActivity(intent);
RelayService.doSendLog = true;

int unsynced = helper.withStatus(getApplicationContext(), TextMessage.INCOMING, TextMessage.RECEIVED).size();
int erroredOut = helper.withStatus(getApplicationContext(), TextMessage.OUTGOING, TextMessage.ERRORED).size();
Expand All @@ -702,8 +676,8 @@ public void onNewSMS(String number, String message) {

if(message.equalsIgnoreCase(keyword + " reset")){
// change the label to true
isReset = true;
Log.d(TAG, "The reset process is set to " + Boolean.toString(isReset));
doReset = true;
Log.d(TAG, "The reset process is set to " + Boolean.toString(doReset));

// start the check service for reset changes to take effect
kickService();
Expand Down Expand Up @@ -798,11 +772,4 @@ public void onSMSSent(String token) {
}

public SMSModem modem;

public static final int UNCHANGED = 0;
public static final int ON = 1;
public static final int OFF = -1;

/** whether the WiFi network is set */
private int m_targetWifiState = UNCHANGED;
}

0 comments on commit dce5490

Please sign in to comment.