How to build an Energy Monitoring Android App p1

Glyn and I have wanted to write an android app to make it easier to access energy monitoring data from phones and tablets for sometime.

Last year, we took part in a student project to develop an Emoncms Android App with Mathew Keegan, who, at the time, was studying at Aberystwyth University. Mathew made good progress on the foundations of the app which I've uploaded to github here: https://github.com/emoncms/AndroidAppDev/tree/master/MathewKeeganAberUni

I've been trying to learn Android app programming to understand what Mathew has developed. I followed a couple of Hello World tutorials, explored networking and how to update the display. I've written my notes as a tutorial: How to build an Energy Monitoring Android App part 1 here:

Tutorial: How to build an Energy Monitoring Android App part 1

I'm going to try and continue development in this style by writing tutorials on how to do each step.

I think everyone should all be able to build their own software if they want to. Given the rising use of tablets and mobiles as our personal computing devices, having at least a basic understanding of how to build an app is enlightening, and it's satisfying to see the results on your phone. Even if you've only dabbled in software before, I encourage you to try the tutorial. Please ask if anything needs clarifying. Feel free to send me a github pull request with edits to the tutorial.

My next tutorial will focus on how to use the android graphics canvas to draw a graph that looks like the myelectric graph in the emoncms "myelectric" module.

If you try the tutorial, please let me know how it goes for you.

borpin123's picture

Re: How to build an Energy Monitoring Android App p1

Excellent :)

tingenek's picture

Re: How to build an Energy Monitoring Android App p1

Why not do it in Processing instead? Much simpler Android experience. Get a single reading and display:

String url = "http://emoncms.org/feed/value.json?apikey=[YOURKEY]&id=43834";
float currentReading;
String[] fontList;
PFont androidFont;

void setup() {
size(displayWidth, displayHeight);
smooth();
fontList = PFont.list();
androidFont = createFont(fontList[0], 40, true);
textFont(androidFont);
//Get latest reading
getReading();
}

void draw() {
background(0);
text("KWh: " + currentReading,20,40);
}

void getReading() {
String lines[] = loadStrings(url);
currentReading =  Float.parseFloat(split(lines[0], '"')[1]); 
}

 

TrystanLea's picture

Re: How to build an Energy Monitoring Android App p1

@tingenek, Interesting! thanks for the snippet

TrystanLea's picture

Re: How to build an Energy Monitoring Android App p1

@tingenek, would you be interested in writing a tutorial on using processing to build the app? I know it creates more work for us but I think it would be great to have tutorials on writing this in processing and android java, that way we can learn about the different approaches and have an understanding of how we might achieve the same result via different approaches, advantages, disadvantages etc, I've added the android app so far to the new software part in building blocks: http://openenergymonitor.org/emon/buildingblocks It would be amazing to have a processing tutorial there too.

tingenek's picture

Re: How to build an Energy Monitoring Android App p1

Happy to. 

Is there a "demo" feed I can read to save me having to make/update one that I can use in the code? Happily, you can use MQTT with Processing as well so might be handy for later :-) 

tgmaxx's picture

Re: How to build an Energy Monitoring Android App p1

Great work Trystan!

 

TrystanLea's picture

Re: How to build an Energy Monitoring Android App p1

TrystanLea's picture

Re: How to build an Energy Monitoring Android App p1

Been working on the next part, tutorial on drawing a myelectric style graph using canvas, tried to keep the first part generic so that its applicable for java, processing, javascript:

https://github.com/openenergymonitor/documentation/blob/master/BuildingB...

tingenek's picture

Re: How to build an Energy Monitoring Android App p1

Great. Just to make sure I read the api correctly, is this the right way to get the readings for the last seven days?
http://emoncms.org/feed/data.json?apikey=7f1b46367a013db07d2d65e588d2ad9...

borpin123's picture

Re: How to build an Energy Monitoring Android App p1

Have you looked at aChartEngine for the charts? Trying to get my head around it :) Not too much in the way of tutorials that I have found.

TrystanLea's picture

Re: How to build an Energy Monitoring Android App p1

@tingenek, sounds like your making good progress if your getting historical data! This is the api you want, this will request the average daily power in watts from feed 43348 which is a power feed. You can then convert average daily power to kWh by multiplying by 0.024.

http://emoncms.org/feed/average.json?&apikey=7f1b46367a013db07d2d65e588d...

Alternatively you could request the watt hour count at the end of each day with the same api but feed 43402. But maybe its easier to start with the power feed approach for now? Looking forward to seeing the processing app, Il get processing installed on my laptop here.

@borpin123, havent tried aChartEngine, looks interesting!

Sergegsx's picture

Re: How to build an Energy Monitoring Android App p1

Trystan I would like to thank you once again for your excellent work and dedication on very good documentation.

I have been wanting to start Android programming for ages, and your first tutorial finally made me start learning. Thanks !

After following you first tutorial I got everything working, but it does not take long for the app to freeze. By adding some extra debuggin I found this...

String urlstring = params[0];
   Log.i("EmonLog", "URL Instance...");
   URL url = new URL(urlstring);
   Log.i("EmonLog", "HTTP Connecting: " + urlstring);
   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

   try {
    Log.i("EmonLog", "InputStream reader");

    InputStream reader = new BufferedInputStream(
      urlConnection.getInputStream());
    Log.i("EmonLog", "Saving to text variable");

    String text = "";
    int i = 0;
    while ((i = reader.read()) != -1) {
     text += (char) i;
    }
    Log.i("EmonLog", "HTTP Response: " + text);
    result = text;

 

 

The LogCat...

 

06-06 00:15:20.833: I/EmonLog(10090): Periodic
06-06 00:15:20.833: I/EmonLog(10090): URL Instance...
06-06 00:15:20.833: I/EmonLog(10090): HTTP Connecting: http://emoncms.org/feed/value.json?apikey=0xxxxxxxxxxxxxxxx03669b5676abf...
06-06 00:15:20.833: I/EmonLog(10090): InputStream reader
06-06 00:15:21.044: I/EmonLog(10090): Parsing the reader
06-06 00:15:21.044: I/EmonLog(10090): HTTP Response: "2640.39"
06-06 00:15:21.044: I/EmonLog(10090): HTTP Disconnecting
06-06 00:15:21.044: I/EmonLog(10090): Periodic 2640.39
06-06 00:15:21.044: I/EmonLog(10090): UIHandler 2640.39
06-06 00:15:21.286: I/EmonLog(10090): Periodic
06-06 00:15:21.286: I/EmonLog(10090): URL Instance...
06-06 00:15:21.286: I/EmonLog(10090): HTTP Connecting: http://emoncms.org/feed/value.json?apikey=0xxxxxxxxxxxxxxxxxc03669b5676a...
06-06 00:15:21.286: I/EmonLog(10090): InputStream reader

 

I have run multiple tests and it always get frozen in InputStream reader, therefore not reaching the next log line which I have called "Saving to text variable".

Anyone has an idea on whats going on?

Thanks and once again, congrats !

Sergegsx's picture

Re: How to build an Energy Monitoring Android App p1

seems like this is helping quite a lot so far, will continue testing...

 

HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

   try {
    Log.i("EmonLog", "InputStream reader");
    urlConnection.setConnectTimeout(5000);
    urlConnection.setReadTimeout(5000);

    InputStream reader = new BufferedInputStream(urlConnection.getInputStream());

 

I have added a counter on the number of updates, will leave it on and see for how long it goes without freezing.

TrystanLea's picture

Re: How to build an Energy Monitoring Android App p1

Thankyou Sergegsx, hearing that makes it worth it to write it! I got that issue too so great to hear you've got a fix, is it still working today?

Sergegsx's picture

Re: How to build an Energy Monitoring Android App p1

Trystan the truth is I have learned so much from your site, from you and from many members of the forum like Robert Wall, calypso, and others. I cant express my gratitude!

Regarding the "fix" it is working great ! It has been working ever since I posted without freezing, so yeah it works. I have noticed that from time to time the value of power appears blank, I guess due to a problem in the response from the server. I will try to add a check in which if the value obtained is empty or "" then do not update the value.

also, as well as the update counter (which is really useful for this test program) I want to add a "last update x seconds ago".

I am on my firsts steps on Android but really happy and very thankful cause it was your tutorial which made me decide on finally start learning (had been in my "to do" list for ...years).

Regards.

 

edit: works...

 

result = result.replaceAll("\"", "");
    if (result == ""){
     Log.i("EmonLog", "**** EMPTY VALUE " + result);
    } else {
    powervalue = result;
    }
   
    Log.i("EmonLog", "Periodic " + powervalue);
    counter_updates ++;

tingenek's picture

Re: How to build an Energy Monitoring Android App p1

Afternoon's coding in Processing now on github: https://github.com/Tingenek/emoncms2/tree/master

Very rough first draft/hardcoded/minimal error handling. Works on my SII phone with android 2.35.

You don't need a phone to try it out as it will work on a desktop just as well.

TrystanLea's picture

Re: How to build an Energy Monitoring Android App p1

Thanks Sergegsx, Good idea to have an last updated seconds ago. Maybe there could be some kind of indicator that turns red if it fails to fetch an update more than 3 or so times consecutively.

@Tingenek, looks brilliant! Il try and get it running here, still need to install processing.

 

tingenek's picture

Re: How to build an Energy Monitoring Android App p1

Let me know how you get on.

Processing can be a bit picky about what android sdk bits you install. 

 

ewiandr's picture

Re: How to build an Energy Monitoring Android App p1

G'day,

How can i add a second feed to the display?

Thanks

Andy

Sergegsx's picture

Re: How to build an Energy Monitoring Android App p1

Hello,

I hope this tutorials keep coming, I have now learned quite a lot on Android but still a super beginner. Anyway, I thought I should point out an important issue with one piece of the code in this example.

String result = new MyAsyncTask().execute().get();

The purpose of using AsyncTask is to prevent the user interface freezing during the HTTP request (that could take a 2 seconds or more). However, if you use the .get() then it will wait until it gets a response to continue, therefore the main purpose of AsyncTask is lost.

The results should be handled in the onpostexecute inside the AsyncTask. This will be executed whenever the
doInBackground has finished.

Although my knowledge in Android is still extreme small, I hope someone finds this useful, it took me a while to figure everything out.

Thanks Trystan again for your work!

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.