Merge branch 'master' of https://github.uci.edu/rtrimana/smart_home_traffic
[pingpong.git] / Code / Projects / TplinkPlugClient / src / main / java / edu / uci / iotproject / tplinkplug / TplinkPlugWanClient.java
1 package edu.uci.iotproject.tplinkplug;
2
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;
7
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;
13
14 /**
15  * TODO add class documentation.
16  *
17  * @author Janus Varmarken
18  */
19 public class TplinkPlugWanClient {
20
21 //    private Client mRestClient = ClientBuilder.newClient();
22
23     public TplinkPlugWanClient() {
24
25     }
26
27     public void powerOn() {
28         System.out.println(String.format("%s.powerOn() invoked", getClass().getSimpleName()));
29         sendRequest(PlugCommand.ON);
30     }
31
32     public void powerOff() {
33         System.out.println(String.format("%s.powerOff() invoked", getClass().getSimpleName()));
34         sendRequest(PlugCommand.OFF);
35     }
36
37     private void sendRequest(PlugCommand plugCommand) {
38
39         String url = String.format("%s/?token=%s", Configuration.getAppServerUrl(), Configuration.getLoginToken());
40         String payload = buildSetRelayStatePayload(plugCommand);
41
42         try {
43             HttpResponse<JsonNode> response = Unirest.post(url).
44                     header("cache-control", "no-cache").
45                     header("Content-Type", MediaType.APPLICATION_JSON).
46                     body(payload).asJson();
47             String debug = null;
48         } catch (UnirestException e) {
49             e.printStackTrace();
50         }
51
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));
56
57         // TODO actually parse the response.
58         String debugPoint = null;
59     }
60
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);
64     }
65
66     private static enum PlugCommand {
67         ON, OFF
68     }
69 }