1 package edu.uci.iotproject.tplinkplug;
3 import com.mashape.unirest.http.HttpResponse;
4 import com.mashape.unirest.http.JsonNode;
5 import com.mashape.unirest.http.Unirest;
6 import com.mashape.unirest.http.exceptions.UnirestException;
8 import javax.ws.rs.client.Client;
9 import javax.ws.rs.client.ClientBuilder;
10 import javax.ws.rs.client.Entity;
11 import javax.ws.rs.core.MediaType;
12 import javax.ws.rs.core.Response;
15 * TODO add class documentation.
17 * @author Janus Varmarken
19 public class TplinkPlugWanClient {
21 // private Client mRestClient = ClientBuilder.newClient();
23 public TplinkPlugWanClient() {
27 public void powerOn() {
28 System.out.println(String.format("%s.powerOn() invoked", getClass().getSimpleName()));
29 sendRequest(PlugCommand.ON);
32 public void powerOff() {
33 System.out.println(String.format("%s.powerOff() invoked", getClass().getSimpleName()));
34 sendRequest(PlugCommand.OFF);
37 private void sendRequest(PlugCommand plugCommand) {
39 String url = String.format("%s/?token=%s", Configuration.getAppServerUrl(), Configuration.getLoginToken());
40 String payload = buildSetRelayStatePayload(plugCommand);
43 HttpResponse<JsonNode> response = Unirest.post(url).
44 header("cache-control", "no-cache").
45 header("Content-Type", MediaType.APPLICATION_JSON).
46 body(payload).asJson();
48 } catch (UnirestException e) {
52 // Response response = mRestClient.target(url).request(MediaType.APPLICATION_JSON).
53 // header("cache-control", "no-cache").
54 // header("Content-Type", MediaType.APPLICATION_JSON).
55 // post(Entity.text(payload));
57 // TODO actually parse the response.
58 String debugPoint = null;
61 private String buildSetRelayStatePayload(PlugCommand command) {
62 return String.format("{ \"method\":\"passthrough\", \"params\": { \"deviceId\": \"%s\", \"requestData\": \"{\\\"system\\\":{\\\"set_relay_state\\\":{\\\"state\\\":%d}}}\"}}",
63 Configuration.getDeviceId(), command.equals(PlugCommand.ON) ? 1 : 0);
66 private static enum PlugCommand {