From the help of user goobering, based on mattrichardson.com and Flask RESTful documentation. I have solved the problem. Here is my solution for anyone who face the same problem. First write a python file in the raspberry pi (with GrovePi github repositories pre-installed for sensor reading).
from flask import Flask
from flask_restful import Resource, Api
import grovepi
app = Flask(__name__)
api = Api(app)
sensor = 7
class TempHum(Resource):
def get(self):
[temp,hum] = grovepi.dht(sensor,0)
return {'temperature' : temp,
'humidity' : hum }
api.add_resource(TempHum, '/')
if __name__ = "__main__":
app.run(host='0.0.0.0', port=80, debug=True)
then run the python file, the raspberry pi will now act as a server. Type:
hostname -I
to get the ip address for the raspberry pi. Then whenever someone send a GET request to this ip address, it will return a temperature and humidity reading in JSON format.
{ "humidity" : 44, "temperature" : 25 }
Below is my java code for getting the readings in Eclipse every 5 seconds. A JSON parser is used to parsed the result return from the raspberry pi.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.json.*;
public class Monitor {
public static HttpURLConnection con;
public static URL url;
public static String url_string = "http://192.168.1.114";
public static void main(String[] args) {
List<Double> temperature = new ArrayList<>();
List<Double> humidity = new ArrayList<>();
for (int i = 0; i < 10; i++) {
try {
url = new URL(url_string);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.connect();
InputStream is = con.getInputStream();
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
JSONObject obj = new JSONObject(sb.toString());
JSONParser parser = new JSONParser();
double[] readings = parser.parseReading(obj);
temperature.add(readings[0]);
humidity.add(readings[1]);
br.close();
Thread.sleep(5000);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i+" read success.");
}
for(int i =0;i<10;i++){
System.out.println("Temperature: "+temperature.get(i)+"C. Humidity: "+humidity.get(i)+"%.");
}
}
}