Android Open Source - AGOGCyberStat Motison Net Task






From Project

Back to project page AGOGCyberStat.

License

The source code is released under:

MIT License

If you think the Android project AGOGCyberStat listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.agog.cyberstat;
//from   w  ww. ja  v a 2  s.  co  m
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import com.agog.cyberstat.R;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.Notification.Builder;
import android.app.Notification.InboxStyle;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import me.allenz.androidapplog.Logger;
import me.allenz.androidapplog.LoggerFactory;
import android.database.Cursor;

/**
 * 
 * @author greg@agog.com
 *
 *  Drive the Motison webapp server pages from an Android Client and set the current target temperature.
 *  
 *      new MotisonNetTask(this.mContext).execute(String email, String password,Trigger tr,
 *        String temperature, String notify);
 *        
   * @param email   Motison webapp username
   * @param password Motison webapp passowrd
   * @param tr     Trigger to control notification settings
   * @param temperature  Target temperature as a string
   * @param notify      Extra suffix to notifiction contect
 */

public class MotisonNetTask extends AsyncTask<Object, Object, Object> {
  private class httppost {
    String url;
    String contenttype;
    String send;
    String received;
    int    responsecode;

    httppost(String url,String contenttype,String send)
    {
      super();
      this.url = url;
      this.contenttype = contenttype;
      this.send = send;
    }

  }


  private static final Logger logger = LoggerFactory.getLogger();
  private static final String URL_AUTH ="https://thermostat.motison.com/auth/login";
  private static final String URL_QUICKDATA ="https://thermostat.motison.com/device-status/quickdata/format/xml";
  private static final String URL_POSTQUICKDATA ="https://thermostat.motison.com/device-status/postquickdata/format/xml";

  private static  int sNid = 2;


  private Context mContext;
  public MotisonNetTask(Context context) {
    this.mContext = context;
  }


  protected void onPreExecute(){
  }

  /* (non-Javadoc)
   * @see android.os.AsyncTask#doInBackground(Params[])
   */
  @Override
  protected Object doInBackground(Object... arg0) {

    // We need to make sure we save the PHP session cookie
    CookieManager cookieManager = new CookieManager();  
    CookieHandler.setDefault(cookieManager);

    String email = (String)arg0[0];
    String password = (String)arg0[1];
    Trigger tr = (Trigger)arg0[2];
    String newtemp = (String)arg0[3];
    String notifytitle = (String)arg0[4];


    int responsecode = Authenticate(email,password);

    if(responsecode == 302) {
      String xmlstring = GetData();
      logger.debug("GetData returns " + xmlstring);
      if(xmlstring != null) {
        MotisonXML mx = new MotisonXML();
        Boolean nochange = mx.setXML(xmlstring,newtemp);
        String nstr = mx.getNotifyString();
        logger.debug("nstr " + nstr);
        notifyUser(nstr + " " + notifytitle, tr);

        String newxml = mx.getXML();
        logger.debug("newxml " + newxml);

        if(!nochange) {
          httppost hp = SetData(newxml);
          logger.debug("SetData " + hp.received);
          if(hp.received == null || !hp.received.equals("<result>passed</result>")) {
            notifyUser("Failed changing settings",null);
          }
        }
      }
      else {
        notifyUser("Failed reading data from server",null);                
      }
    }
    else if(responsecode == 0) {
      notifyUser("Network error on authentication",null);       
    }
    else {
      notifyUser("Auth. failure check username and password",null);       
    }


    return null;
  }


  protected int Authenticate(String email,String password)
  {
    try {
      email = URLEncoder.encode(email, "UTF-8");
      password = URLEncoder.encode(password, "UTF-8");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }

    String msg = "email="+ email + "&password=" + password + "&rememberMe=0&loginBtn=Login";

    httppost hp = new httppost(URL_AUTH,"application/x-www-form-urlencoded",msg);
    dopost(hp);
    if(hp.responsecode == 200) {
      // We are emulating a webapp protocol. Sometimes on the first try we receive the login screen.
      dopost(hp);
      if(hp.responsecode == 200) {
        logger.error("Authenticate: " + hp.received);
      }
    }
    return(hp.responsecode);
  }

  protected String GetData()
  {
    httppost hp = new httppost(URL_QUICKDATA,"application/xml",null);
    dopost(hp);
    return(hp.received == null ? "" : hp.received);
  }

  protected httppost SetData(String newxml)
  {
    httppost hp = new httppost(URL_POSTQUICKDATA,"application/xml",newxml);
    dopost(hp);
    return(hp);
  }


  protected void dopost(httppost hp)
  {
    // send POST message
    for(int retry = 0; retry < 5; retry++) {
      hp.responsecode = 0;
      hp.received = null;

      try {
        Thread.sleep(1000*retry*retry);
      } catch (InterruptedException e1) {
        e1.printStackTrace();
      }

      try {
        URL url = new URL(hp.url);
        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
        // Prepare method
        httpConnection.setRequestMethod("POST");
        // do not follow possible redirects
        HttpURLConnection.setFollowRedirects(false);
        // Prepare for input and output 
        httpConnection.setDoInput(true);
        httpConnection.setDoOutput(true);
        // Turn off caching
        httpConnection.setUseCaches(false);
        // content type
        httpConnection.setRequestProperty("Content-Type", hp.contenttype);
        if(hp.send != null) {
          DataOutputStream out = new DataOutputStream(httpConnection.getOutputStream());
          out.writeBytes(hp.send);
          out.flush();
          out.close();
        }

        httpConnection.connect();
        hp.responsecode = httpConnection.getResponseCode();
        logger.debug("retry " + retry + " reponsecode " + hp.responsecode);
        if(hp.responsecode == 302) {
          break;
        }

        if(hp.responsecode == 200) {
          BufferedReader aiResult = new BufferedReader(
              new InputStreamReader(httpConnection.getInputStream()));
          String line;
          StringBuffer responseMessage = new StringBuffer();
          while ((line = aiResult.readLine()) != null) {
            responseMessage.append(line);
          }
          hp.received = responseMessage.toString();
          break;
        }
      }
      catch (MalformedURLException e) {
        logger.error("dopost: " + e);
        e.printStackTrace();
      } catch (IOException e) {
        logger.error("dopost: " + e);
        e.printStackTrace();
      }
    }
  }

  protected void notifyUser(String text,Trigger tr) {
    notifyUser("AGOGCyberStat",tr,text);
  }

  protected Uri lookupRingtone(String title)
  {
    RingtoneManager ringtoneMgr = new RingtoneManager(mContext);
    ringtoneMgr.setType(RingtoneManager.TYPE_NOTIFICATION);
    Cursor cursor = ringtoneMgr.getCursor();

    while(cursor.moveToNext()) {
      Ringtone rt = ringtoneMgr.getRingtone(cursor.getPosition());
      //logger.debug("rt " + rt.getTitle(mContext) + "," + ringtoneMgr.getRingtoneUri(cursor.getPosition()));

      if(rt.getTitle(mContext).equals(title)) {
        return(ringtoneMgr.getRingtoneUri(cursor.getPosition()));
      }
    }
    return RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
  }

  static String mOldNotify[] = new String[4];
  static long mOldNotifyTime[] = new long[4];

  @SuppressLint("InlinedApi")
  protected void notifyUser(String title,Trigger tr,String text) {
        
    /***
    String alltext = mEventsView.getText().toString() + "\n" + new Date() + " " + title + " " + text;
    mEventsView.setText(alltext);
     *****/
    
    for(int i = mOldNotify.length - 1; i > 0; i--) {
      mOldNotify[i] = mOldNotify[i-1];
      mOldNotifyTime[i] = mOldNotifyTime[i-1];
    }
    mOldNotify[0] = text;
    mOldNotifyTime[0] = System.currentTimeMillis() / 1000;

    if(tr == null || tr.notify) {
      Intent notificationIntent = new Intent(mContext, MainActivity.class);

      // The stack builder object will contain an artificial back stack for the
      // started Activity.
      // This ensures that navigating backward from the Activity leads out of
      // your application to the Home screen.
      TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext);
      // Adds the back stack for the Intent (but not the Intent itself)
      stackBuilder.addParentStack(MainActivity.class);
      // Adds the Intent that starts the Activity to the top of the stack
      stackBuilder.addNextIntent(notificationIntent);
      PendingIntent resultPendingIntent =
          stackBuilder.getPendingIntent(
              0,
              PendingIntent.FLAG_UPDATE_CURRENT
              );

      NotificationManager nm = (NotificationManager) mContext
          .getSystemService(Context.NOTIFICATION_SERVICE);

      Builder builder = new Builder(mContext);

      builder.setContentIntent(resultPendingIntent)
      .setAutoCancel(false)
      .setWhen(System.currentTimeMillis())
      .setSmallIcon(R.drawable.ic_launcher)
      .setContentTitle(title)
      .setContentText(text);
      
      builder.setPriority(Notification.PRIORITY_MAX);

      InboxStyle inboxStyle = new Notification.InboxStyle();

      // Sets a title for the Inbox in expanded layout
      inboxStyle.setBigContentTitle(title);

      // Moves events into the expanded layout
      for (int i=0; i < mOldNotify.length && mOldNotify[i] != null; i++) {
        String tstr = "";
        if(i > 0) {
            int j = (int) (mOldNotifyTime[0] - mOldNotifyTime[i]) / 60;
            if(j > 60) {
              j /= 60;
              tstr = j + " Hr";
              if(j > 1)
                tstr += "s";
            }
            else if(j > 0) {
                tstr = j + " Min";
                if(j > 1)
                  tstr += "s";
            }
        }
        inboxStyle.addLine(mOldNotify[i] + " " + tstr);
      }
      // Moves the expanded layout object into the notification object.
      builder.setStyle(inboxStyle);   

      Notification n = builder.build();

      if(tr == null) {
        n.sound =  RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
      }
      else if(tr.sound) {
        n.sound = lookupRingtone(tr.ringtone);
      }

      nm.notify(sNid, n);
    }
  }



  protected void onPostExecute(String result){
  }


}




Java Source Code List

com.agog.cyberstat.BrR.java
com.agog.cyberstat.JSONSettings.java
com.agog.cyberstat.MainActivity.java
com.agog.cyberstat.MotisonNetTask.java
com.agog.cyberstat.MotisonXML.java
com.agog.cyberstat.MyPrefs.java
com.agog.cyberstat.NetR.java
com.agog.cyberstat.Trigger.java
me.allenz.androidapplog.AbstractAppender.java
me.allenz.androidapplog.AbstractLogger.java
me.allenz.androidapplog.AppenderSupportLogger.java
me.allenz.androidapplog.Appender.java
me.allenz.androidapplog.AsyncAppender.java
me.allenz.androidapplog.Configure.java
me.allenz.androidapplog.InternalLogger.java
me.allenz.androidapplog.LogCatAppender.java
me.allenz.androidapplog.LogEvent.java
me.allenz.androidapplog.LogLevel.java
me.allenz.androidapplog.LogTextView.java
me.allenz.androidapplog.LoggerConfig.java
me.allenz.androidapplog.LoggerFactory.java
me.allenz.androidapplog.Logger.java
me.allenz.androidapplog.PropertiesParser.java
me.allenz.androidapplog.ReflectUtils.java
me.allenz.androidapplog.Repository.java
me.allenz.androidapplog.RollingFileAppender.java
me.allenz.androidapplog.TextViewAppender.java