Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
adding websocket functionality
  • Loading branch information
RealZimboGuy committed Jan 14, 2021
1 parent ca8a081 commit 0e0bbdb
Show file tree
Hide file tree
Showing 12 changed files with 609 additions and 6 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@ target/

src/test/java/com/github/realzimboguy/ewelink/api/TestAppPrivate.java
src/test/java/com/github/realzimboguy/ewelink/api/TestApp.java

.idea/
44 changes: 44 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ You must perform a login before calling any other methods, the methods exposed a
public Status setDeviceStatusByName(String name, String status) throws Exception

public Status setDeviceStatus(String deviceId, String status) throws Exception

public void getWebSocket(WssResponse wssResponse) throws Exception

sample

Expand All @@ -64,6 +66,48 @@ sample
System.out.println(eweLink.getDevice("10009ce53b"));

System.out.println(eweLink.setDeviceStatusByName("Pool Tank","off"));
eweLink.getWebSocket(new WssResponse() {
@Override
public void onMessage(String s) {
//if you want the raw json data
System.out.println("on message in test raw:" + s);
}
@Override
public void onMessageParsed(WssRspMsg rsp) {
if (rsp.getError() == null) {
//normal scenario
StringBuilder sb = new StringBuilder();
sb.append("Device:").append(rsp.getDeviceid()).append(" - ");
if (rsp.getParams() != null) {
sb.append("Switch:").append(rsp.getParams().getSwitch()).append(" - ");
sb.append("Voltage:").append(rsp.getParams().getVoltage()).append(" - ");
sb.append("Power:").append(rsp.getParams().getPower()).append(" - ");
sb.append("Current:").append(rsp.getParams().getCurrent()).append(" - ");
}
System.out.println(sb.toString());
} else if (rsp.getError() == 0) {
//this is from a login response
System.out.println("login success");
} else if (rsp.getError() > 0) {
System.out.println("login error:" + rsp.toString());
}
}
@Override
public void onError(String error) {
System.out.println("onError in test, this should never be called");
System.out.println(error);
}
});


} catch (Exception e) {
Expand Down
8 changes: 7 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<groupId>com.github.realzimboguy.ewelink.api</groupId>
<artifactId>ewelink-api-java</artifactId>
<version>2.0.1-RELEASE</version>
<version>2.1.0-RELEASE</version>
<packaging>jar</packaging>

<name>ewelink-api-java</name>
Expand Down Expand Up @@ -78,6 +78,11 @@
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.5.1</version>
</dependency>
</dependencies>


Expand Down Expand Up @@ -120,6 +125,7 @@
</plugin>



<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
Expand Down
70 changes: 65 additions & 5 deletions src/main/java/com/github/realzimboguy/ewelink/api/EweLink.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import com.github.realzimboguy.ewelink.api.model.StatusChange;
import com.github.realzimboguy.ewelink.api.model.login.LoginRequest;
import com.github.realzimboguy.ewelink.api.model.login.LoginResponse;
import com.github.realzimboguy.ewelink.api.wss.WssLogin;
import com.github.realzimboguy.ewelink.api.wss.WssResponse;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand All @@ -14,6 +16,7 @@
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.URI;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
Expand All @@ -25,12 +28,12 @@ public class EweLink {

Logger logger = LoggerFactory.getLogger(EweLink.class);

private String region;
private static String region;
private String email;
private String password;
private int activityTimer;
private String baseUrl = "https://eu-api.coolkit.cc:8080/api/";
private static final String APP_ID = "YzfeftUVcZ6twZw1OoVKPRFYTrGEg01Q";
public static final String APP_ID = "YzfeftUVcZ6twZw1OoVKPRFYTrGEg01Q";
private static final String APP_SECRET = "4G91qSoboqYO4Y0XJ0LPPKIsq8reHdfa";
private static boolean isLoggedIn = false;
private static long lastActivity = 0L;
Expand All @@ -39,8 +42,10 @@ public class EweLink {

private static String accessToken;
private static String apiKey;
private static WssResponse clientWssResponse;


private static EweLinkWebSocketClient eweLinkWebSocketClient = null;
private static Thread webSocketMonitorThread = null;
Gson gson = new Gson();

public EweLink(String region,String email, String password, int activityTimer) {
Expand All @@ -50,8 +55,8 @@ public EweLink(String region,String email, String password, int activityTimer) {
if (region!= null) {
baseUrl = "https://" + region + "-api.coolkit.cc:8080/api/";
}
if (activityTimer == 0) {
activityTimer = 1;
if (activityTimer < 30) {
activityTimer = 30;
}
this.activityTimer = activityTimer;

Expand Down Expand Up @@ -133,6 +138,25 @@ public void login() throws Exception{

}

public void getWebSocket(WssResponse wssResponse) throws Exception {
if (!isLoggedIn){
throw new Exception("Not Logged In, please call login Method");
}

eweLinkWebSocketClient = new EweLinkWebSocketClient(new URI("wss://"+ region+"-pconnect3.coolkit.cc:8080/api/ws"));
clientWssResponse = wssResponse;
eweLinkWebSocketClient.setWssResponse(clientWssResponse);
eweLinkWebSocketClient.setWssLogin(gson.toJson(new WssLogin(accessToken,apiKey,APP_ID,Util.getNonce())));
eweLinkWebSocketClient.connect();

if(webSocketMonitorThread == null) {
webSocketMonitorThread = new Thread(new WebSocketMonitor());
webSocketMonitorThread.start();
}


}

public Devices getDevices() throws Exception {

if (!isLoggedIn){
Expand Down Expand Up @@ -442,6 +466,42 @@ private static String getAuthMac (String data) throws UnsupportedEncodingExcepti
}


public class WebSocketMonitor implements Runnable
{

Logger logger = LoggerFactory.getLogger(WebSocketMonitor.class);
Gson gson = new Gson();


@Override
public void run() {

logger.info("Websocket Monitor Thread start");

while (true) {
try {
Thread.sleep(30000);
logger.debug("send websocket ping");
eweLinkWebSocketClient.send("ping");

} catch (Exception e) {
logger.error("Error in sening websocket ping:",e);
logger.info("Try reconnect to websocket");
try {
eweLinkWebSocketClient = new EweLinkWebSocketClient(new URI("wss://"+ region+"-pconnect3.coolkit.cc:8080/api/ws"));
eweLinkWebSocketClient.setWssResponse(clientWssResponse);
eweLinkWebSocketClient.setWssLogin(gson.toJson(new WssLogin(accessToken,apiKey,APP_ID,Util.getNonce())));
eweLinkWebSocketClient.connect();

}catch (Exception c) {
logger.error("Error trying to reconnect:",c);
}
}
}
}
}


}


Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package com.github.realzimboguy.ewelink.api;

import com.github.realzimboguy.ewelink.api.wss.WssLogin;
import com.github.realzimboguy.ewelink.api.wss.WssResponse;
import com.github.realzimboguy.ewelink.api.wss.wssrsp.WssRspMsg;
import com.google.gson.Gson;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;

public class EweLinkWebSocketClient extends WebSocketClient {

Logger logger = LoggerFactory.getLogger(EweLinkWebSocketClient.class);

private WssResponse wssResponse;
private String wssLogin;
Gson gson = new Gson();

public void setWssResponse(WssResponse wssResponse) {
this.wssResponse = wssResponse;
}

public void setWssLogin(String wssLogin) {
this.wssLogin = wssLogin;
}

public EweLinkWebSocketClient(URI serverUri) {
super(serverUri);
}

@Override
public void onOpen(ServerHandshake serverHandshake) {
send(wssLogin);
}

@Override
public void onMessage(String s) {
if (s!= null && s.equalsIgnoreCase("pong")){
//swallow this as its just a ping/pong
logger.debug(s);
}else {
wssResponse.onMessage(s);
wssResponse.onMessageParsed(gson.fromJson(s, WssRspMsg.class));
}
}

@Override
public void onClose(int i, String s, boolean b) {
logger.warn("WS onCloseCalled, system will self-recover {} {} {}",i,s,b);
}

@Override
public void onError(Exception e) {
wssResponse.onError(e.getMessage());
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@

package com.github.realzimboguy.ewelink.api.model.devices;

import com.google.gson.annotations.SerializedName;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
Expand All @@ -9,6 +11,7 @@ public class Params {

private BindInfos bindInfos;
private String sledOnline;
@SerializedName("switch")
private String _switch;
private String power;
private String voltage;
Expand Down Expand Up @@ -269,4 +272,38 @@ public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

@Override
public String toString() {
return "Params{" +
"bindInfos=" + bindInfos +
", sledOnline='" + sledOnline + '\'' +
", _switch='" + _switch + '\'' +
", power='" + power + '\'' +
", voltage='" + voltage + '\'' +
", current='" + current + '\'' +
", fwVersion='" + fwVersion + '\'' +
", staMac='" + staMac + '\'' +
", rssi=" + rssi +
", init=" + init +
", alarmType='" + alarmType + '\'' +
", alarmVValue=" + alarmVValue +
", alarmCValue=" + alarmCValue +
", alarmPValue=" + alarmPValue +
", oneKwh='" + oneKwh + '\'' +
", uiActive=" + uiActive +
", timeZone=" + timeZone +
", version=" + version +
", startup='" + startup + '\'' +
", pulse='" + pulse + '\'' +
", pulseWidth=" + pulseWidth +
", timers=" + timers +
", hundredDaysKwh='" + hundredDaysKwh + '\'' +
", onlyDevice=" + onlyDevice +
", ssid='" + ssid + '\'' +
", bssid='" + bssid + '\'' +
", endTime='" + endTime + '\'' +
", startTime='" + startTime + '\'' +
", additionalProperties=" + additionalProperties +
'}';
}
}
Loading

0 comments on commit 0e0bbdb

Please sign in to comment.