diff --git a/android/app/app.iml b/android/app/app.iml
index 41f9457..fa1da22 100644
--- a/android/app/app.iml
+++ b/android/app/app.iml
@@ -112,12 +112,12 @@
-
+
-
+
\ No newline at end of file
diff --git a/android/app/build.gradle b/android/app/build.gradle
index f7f7700..422363b 100644
--- a/android/app/build.gradle
+++ b/android/app/build.gradle
@@ -7,8 +7,8 @@ android {
applicationId "cc.seeed.iot.ap"
minSdkVersion 16
targetSdkVersion 23
- versionCode 10
- versionName "2.0.3"
+ versionCode 12
+ versionName "2.1.1"
}
buildTypes {
release {
diff --git a/android/app/src/main/java/cc/seeed/iot/MyApplication.java b/android/app/src/main/java/cc/seeed/iot/MyApplication.java
index ae6f289..803a66b 100644
--- a/android/app/src/main/java/cc/seeed/iot/MyApplication.java
+++ b/android/app/src/main/java/cc/seeed/iot/MyApplication.java
@@ -5,7 +5,6 @@
import cc.seeed.iot.datastruct.User;
import cc.seeed.iot.util.Common;
-import cc.seeed.iot.webapi.ExchangeApi;
import cc.seeed.iot.webapi.IotApi;
/**
@@ -52,7 +51,6 @@ public void onCreate() {
private void init() {
IotApi.SetServerUrl(ota_server_url);
- ExchangeApi.SetServerUrl(exchange_server_url);
}
public Boolean getLoginState() {
diff --git a/android/app/src/main/java/cc/seeed/iot/datastruct/Constant.java b/android/app/src/main/java/cc/seeed/iot/datastruct/Constant.java
index 899e5d7..3728e38 100644
--- a/android/app/src/main/java/cc/seeed/iot/datastruct/Constant.java
+++ b/android/app/src/main/java/cc/seeed/iot/datastruct/Constant.java
@@ -9,6 +9,11 @@ public class Constant {
"All",
"Input",
"Output",
+ "GPIO",
+ "ANALOG",
+ "UART",
+ "I2C",
+ "EVENT",
};
diff --git a/android/app/src/main/java/cc/seeed/iot/esptouch/EsptouchResult.java b/android/app/src/main/java/cc/seeed/iot/esptouch/EsptouchResult.java
deleted file mode 100644
index bb1490f..0000000
--- a/android/app/src/main/java/cc/seeed/iot/esptouch/EsptouchResult.java
+++ /dev/null
@@ -1,51 +0,0 @@
-package cc.seeed.iot.esptouch;
-
-import java.net.InetAddress;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-public class EsptouchResult implements IEsptouchResult {
-
- private final boolean mIsSuc;
- private final String mBssid;
- private final InetAddress mInetAddress;
- private AtomicBoolean mIsCancelled;
-
- /**
- * Constructor of EsptouchResult
- *
- * @param isSuc whether the esptouch task is executed suc
- * @param bssid the device's bssid
- * @param inetAddress the device's ip address
- */
- public EsptouchResult(boolean isSuc, String bssid,InetAddress inetAddress) {
- this.mIsSuc = isSuc;
- this.mBssid = bssid;
- this.mInetAddress = inetAddress;
- this.mIsCancelled = new AtomicBoolean(false);
- }
-
- @Override
- public boolean isSuc() {
- return this.mIsSuc;
- }
-
- @Override
- public String getBssid() {
- return this.mBssid;
- }
-
- @Override
- public boolean isCancelled() {
- return mIsCancelled.get();
- }
-
- public void setIsCancelled(boolean isCancelled){
- this.mIsCancelled.set(isCancelled);
- }
-
- @Override
- public InetAddress getInetAddress() {
- return this.mInetAddress;
- }
-
-}
diff --git a/android/app/src/main/java/cc/seeed/iot/esptouch/EsptouchTask.java b/android/app/src/main/java/cc/seeed/iot/esptouch/EsptouchTask.java
deleted file mode 100644
index 399df3a..0000000
--- a/android/app/src/main/java/cc/seeed/iot/esptouch/EsptouchTask.java
+++ /dev/null
@@ -1,82 +0,0 @@
-package cc.seeed.iot.esptouch;
-
-import android.content.Context;
-
-import cc.seeed.iot.esptouch.task.EsptouchTaskParameter;
-import cc.seeed.iot.esptouch.task.__EsptouchTask;
-import cc.seeed.iot.esptouch.task.IEsptouchTaskParameter;
-
-import java.util.List;
-
-
-public class EsptouchTask implements IEsptouchTask {
-
- public __EsptouchTask _mEsptouchTask;
- private IEsptouchTaskParameter _mParameter;
-
- /**
- * Constructor of EsptouchTask
- *
- * @param apSsid
- * the Ap's ssid
- * @param apBssid
- * the Ap's bssid
- * @param apPassword
- * the Ap's password
- * @param isSsidHidden
- * whether the Ap's ssid is hidden
- * @param context
- * the Context of the Application
- */
- public EsptouchTask(String apSsid, String apBssid, String apPassword,boolean isSsidHidden, Context context) {
- _mParameter = new EsptouchTaskParameter();
- _mEsptouchTask = new __EsptouchTask(apSsid, apBssid, apPassword, context, _mParameter, isSsidHidden);
- }
-
- /**
- * Constructor of EsptouchTask
- *
- * @param apSsid
- * the Ap's ssid
- * @param apBssid
- * the Ap's bssid
- * @param apPassword
- * the Ap's password
- * @param isSsidHidden
- * whether the Ap's ssid is hidden
- * @param timeoutMillisecond(it should be >= 10000+8000)
- * millisecond of total timeout
- * @param context
- * the Context of the Application
- */
- public EsptouchTask(String apSsid, String apBssid, String apPassword,boolean isSsidHidden,int timeoutMillisecond, Context context) {
- _mParameter = new EsptouchTaskParameter();
- _mParameter.setWaitUdpTotalMillisecond(timeoutMillisecond);
- _mEsptouchTask = new __EsptouchTask(apSsid, apBssid, apPassword, context, _mParameter, isSsidHidden);
- }
-
-
- @Override
- public void interrupt() {
- _mEsptouchTask.interrupt();
- }
-
- @Override
- public IEsptouchResult executeForResult() throws RuntimeException {
- return _mEsptouchTask.executeForResult();
- }
-
- @Override
- public boolean isCancelled() {
- return _mEsptouchTask.isCancelled();
- }
-
- @Override
- public List executeForResults(int expectTaskResultCount)
- throws RuntimeException {
- if (expectTaskResultCount <= 0) {
- expectTaskResultCount = Integer.MAX_VALUE;
- }
- return _mEsptouchTask.executeForResults(expectTaskResultCount);
- }
-}
diff --git a/android/app/src/main/java/cc/seeed/iot/esptouch/IEsptouchResult.java b/android/app/src/main/java/cc/seeed/iot/esptouch/IEsptouchResult.java
deleted file mode 100644
index 1867c93..0000000
--- a/android/app/src/main/java/cc/seeed/iot/esptouch/IEsptouchResult.java
+++ /dev/null
@@ -1,34 +0,0 @@
-package cc.seeed.iot.esptouch;
-
-import java.net.InetAddress;
-
-public interface IEsptouchResult {
-
- /**
- * check whether the esptouch task is executed suc
- *
- * @return whether the esptouch task is executed suc
- */
- boolean isSuc();
-
- /**
- * get the device's bssid
- *
- * @return the device's bssid
- */
- String getBssid();
-
- /**
- * check whether the esptouch task is cancelled by user
- *
- * @return whether the esptouch task is cancelled by user
- */
- boolean isCancelled();
-
- /**
- * get the ip address of the device
- *
- * @return the ip device of the device
- */
- InetAddress getInetAddress();
-}
diff --git a/android/app/src/main/java/cc/seeed/iot/esptouch/IEsptouchTask.java b/android/app/src/main/java/cc/seeed/iot/esptouch/IEsptouchTask.java
deleted file mode 100644
index 9b446ed..0000000
--- a/android/app/src/main/java/cc/seeed/iot/esptouch/IEsptouchTask.java
+++ /dev/null
@@ -1,49 +0,0 @@
-package cc.seeed.iot.esptouch;
-
-import java.util.List;
-
-public interface IEsptouchTask {
-
- /**
- * Interrupt the Esptouch Task when User tap back or close the Application.
- */
- void interrupt();
-
- /**
- * Note: !!!Don't call the task at UI Main Thread or RuntimeException will
- * be thrown Execute the Esptouch Task and return the result
- *
- * Smart Config v2.2 support the API
- *
- * @return the IEsptouchResult
- * @throws RuntimeException
- */
- IEsptouchResult executeForResult() throws RuntimeException;
-
- /**
- * Note: !!!Don't call the task at UI Main Thread or RuntimeException will
- * be thrown Execute the Esptouch Task and return the result
- *
- * Smart Config v2.2 support the API
- *
- * It will be blocked until the client receive result count >= expectTaskResultCount.
- * If it fail, it will return one fail result will be returned in the list.
- * If it is cancelled while executing,
- * if it has received some results, all of them will be returned in the list.
- * if it hasn't received any results, one cancel result will be returned in the list.
- *
- * @param expectTaskResultCount
- * the expect result count(if expectTaskResultCount <= 0,
- * expectTaskResultCount = Integer.MAX_VALUE)
- * @return the list of IEsptouchResult
- * @throws RuntimeException
- */
- List executeForResults(int expectTaskResultCount) throws RuntimeException;
-
- /**
- * check whether the task is cancelled by user
- *
- * @return whether the task is cancelled by user
- */
- boolean isCancelled();
-}
diff --git a/android/app/src/main/java/cc/seeed/iot/esptouch/protocol/DataCode.java b/android/app/src/main/java/cc/seeed/iot/esptouch/protocol/DataCode.java
deleted file mode 100644
index aab1305..0000000
--- a/android/app/src/main/java/cc/seeed/iot/esptouch/protocol/DataCode.java
+++ /dev/null
@@ -1,87 +0,0 @@
-package cc.seeed.iot.esptouch.protocol;
-
-import cc.seeed.iot.esptouch.util.CRC8;
-import cc.seeed.iot.esptouch.task.ICodeData;
-import cc.seeed.iot.esptouch.util.ByteUtil;
-
-/**
- * one data format:(data code should have 2 to 65 data)
- *
- * control byte high 4 bits low 4 bits
- * 1st 9bits: 0x0 crc(high) data(high)
- * 2nd 9bits: 0x1 sequence header
- * 3rd 9bits: 0x0 crc(low) data(low)
- *
- * sequence header: 0,1,2,...
- *
- * @author afunx
- *
- */
-public class DataCode implements ICodeData{
-
- public static final int DATA_CODE_LEN = 6;
-
- private static final int INDEX_MAX = 127;
-
- private final byte mSeqHeader;
- private final byte mDataHigh;
- private final byte mDataLow;
- // the crc here means the crc of the data and sequence header be transformed
- // it is calculated by index and data to be transformed
- private final byte mCrcHigh;
- private final byte mCrcLow;
-
- /**
- * Constructor of DataCode
- * @param u8 the character to be transformed
- * @param index the index of the char
- */
- public DataCode(char u8, int index) {
- if (index > INDEX_MAX) {
- throw new RuntimeException("index > INDEX_MAX");
- }
- byte[] dataBytes = ByteUtil.splitUint8To2bytes(u8);
- mDataHigh = dataBytes[0];
- mDataLow = dataBytes[1];
- CRC8 crc8 = new CRC8();
- crc8.update(ByteUtil.convertUint8toByte(u8));
- crc8.update(index);
- byte[] crcBytes = ByteUtil.splitUint8To2bytes((char) crc8.getValue());
- mCrcHigh = crcBytes[0];
- mCrcLow = crcBytes[1];
- mSeqHeader = (byte) index;
- }
-
- @Override
- public byte[] getBytes() {
- byte[] dataBytes = new byte[DATA_CODE_LEN];
- dataBytes[0] = 0x00;
- dataBytes[1] = ByteUtil.combine2bytesToOne(mCrcHigh,mDataHigh);
- dataBytes[2] = 0x01;
- dataBytes[3] = mSeqHeader;
- dataBytes[4] = 0x00;
- dataBytes[5] = ByteUtil.combine2bytesToOne(mCrcLow, mDataLow);
- return dataBytes;
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- byte[] dataBytes = getBytes();
- for (int i = 0; i < DATA_CODE_LEN; i++) {
- String hexString = ByteUtil.convertByte2HexString(dataBytes[i]);
- sb.append("0x");
- if (hexString.length() == 1) {
- sb.append("0");
- }
- sb.append(hexString).append(" ");
- }
- return sb.toString();
- }
-
- @Override
- public char[] getU8s() {
- throw new RuntimeException("DataCode don't support getU8s()");
- }
-
-}
diff --git a/android/app/src/main/java/cc/seeed/iot/esptouch/protocol/DatumCode.java b/android/app/src/main/java/cc/seeed/iot/esptouch/protocol/DatumCode.java
deleted file mode 100644
index 65b662b..0000000
--- a/android/app/src/main/java/cc/seeed/iot/esptouch/protocol/DatumCode.java
+++ /dev/null
@@ -1,145 +0,0 @@
-package cc.seeed.iot.esptouch.protocol;
-
-import cc.seeed.iot.esptouch.util.CRC8;
-import cc.seeed.iot.esptouch.util.EspNetUtil;
-import cc.seeed.iot.esptouch.task.ICodeData;
-import cc.seeed.iot.esptouch.util.ByteUtil;
-
-import java.net.InetAddress;
-
-public class DatumCode implements ICodeData {
-
- // define by the Esptouch protocol, all of the datum code should add 1 at last to prevent 0
- private static final int EXTRA_LEN = 40;
- private static final int EXTRA_HEAD_LEN = 5;
-
- private final DataCode[] mDataCodes;
-
- /**
- * Constructor of DatumCode
- * @param apSsid the Ap's ssid
- * @param apBssid the Ap's bssid
- * @param apPassword the Ap's password
- * @param ipAddress the ip address of the phone or pad
- * @param isSsidHidden whether the Ap's ssid is hidden
- */
- public DatumCode(String apSsid, String apBssid, String apPassword,
- InetAddress ipAddress, boolean isSsidHidden) {
- // Data = total len(1 byte) + apPwd len(1 byte) + SSID CRC(1 byte) +
- // BSSID CRC(1 byte) + TOTAL XOR(1 byte)+ ipAddress(4 byte) + apPwd + apSsid apPwdLen <=
- // 105 at the moment
-
- // total xor
- char totalXor = 0;
-
- char apPwdLen = (char) ByteUtil.getBytesByString(apPassword).length;
- CRC8 crc = new CRC8();
- crc.update(ByteUtil.getBytesByString(apSsid));
- char apSsidCrc = (char) crc.getValue();
-
- crc.reset();
- crc.update(EspNetUtil.parseBssid2bytes(apBssid));
- char apBssidCrc = (char) crc.getValue();
-
- char apSsidLen = (char) ByteUtil.getBytesByString(apSsid).length;
- // hostname parse
- String ipAddrStrs[] = ipAddress.getHostAddress().split("\\.");
- int ipLen = ipAddrStrs.length;
-
- char ipAddrChars[] = new char[ipLen];
- // only support ipv4 at the moment
- for (int i = 0; i < ipLen; ++i) {
- ipAddrChars[i] = (char) Integer.parseInt(ipAddrStrs[i]);
- }
-
-
- char _totalLen = (char) (EXTRA_HEAD_LEN + ipLen + apPwdLen + apSsidLen);
- char totalLen = isSsidHidden ? (char) (EXTRA_HEAD_LEN + ipLen + apPwdLen + apSsidLen)
- : (char) (EXTRA_HEAD_LEN + ipLen + apPwdLen);
-
- // build data codes
- mDataCodes = new DataCode[totalLen];
- mDataCodes[0] = new DataCode(_totalLen, 0);
- totalXor ^= _totalLen;
- mDataCodes[1] = new DataCode(apPwdLen, 1);
- totalXor ^= apPwdLen;
- mDataCodes[2] = new DataCode(apSsidCrc, 2);
- totalXor ^= apSsidCrc;
- mDataCodes[3] = new DataCode(apBssidCrc, 3);
- totalXor ^= apBssidCrc;
- mDataCodes[4] = null;
- for (int i = 0; i < ipLen; ++i) {
- mDataCodes[i + EXTRA_HEAD_LEN] = new DataCode(ipAddrChars[i], i + EXTRA_HEAD_LEN);
- totalXor ^= ipAddrChars[i];
- }
-
- byte[] apPwdBytes = ByteUtil.getBytesByString(apPassword);
- char[] apPwdChars = new char[apPwdBytes.length];
- for (int i = 0;i < apPwdBytes.length; i++) {
- apPwdChars[i] = ByteUtil.convertByte2Uint8(apPwdBytes[i]);
- }
- for (int i = 0; i < apPwdChars.length; i++) {
- mDataCodes[i + EXTRA_HEAD_LEN + ipLen] = new DataCode(
- apPwdChars[i], i + EXTRA_HEAD_LEN + ipLen);
- totalXor ^= apPwdChars[i];
- }
-
- byte[] apSsidBytes = ByteUtil.getBytesByString(apSsid);
- char[] apSsidChars = new char[apSsidBytes.length];
-
- // totalXor will xor apSsidChars no matter whether the ssid is hidden
- for (int i = 0; i < apSsidBytes.length; i++) {
- apSsidChars[i] = ByteUtil.convertByte2Uint8(apSsidBytes[i]);
- totalXor ^= apSsidChars[i];
- }
-
- if (isSsidHidden) {
- for (int i = 0; i < apSsidChars.length; i++) {
- mDataCodes[i + EXTRA_HEAD_LEN + ipLen + apPwdLen] = new DataCode(
- apSsidChars[i], i + EXTRA_HEAD_LEN + ipLen + apPwdLen);
- }
- }
-
- // set total xor last
- mDataCodes[4] = new DataCode(totalXor, 4);
- }
-
- @Override
- public byte[] getBytes() {
- byte[] datumCode = new byte[mDataCodes.length * DataCode.DATA_CODE_LEN];
- for (int i = 0; i < mDataCodes.length; i++) {
- System.arraycopy(mDataCodes[i].getBytes(), 0, datumCode, i
- * DataCode.DATA_CODE_LEN, DataCode.DATA_CODE_LEN);
- }
- return datumCode;
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- byte[] dataBytes = getBytes();
- for (int i = 0; i < dataBytes.length; i++) {
- String hexString = ByteUtil.convertByte2HexString(dataBytes[i]);
- sb.append("0x");
- if (hexString.length() == 1) {
- sb.append("0");
- }
- sb.append(hexString).append(" ");
- }
- return sb.toString();
- }
-
- @Override
- public char[] getU8s() {
- byte[] dataBytes = getBytes();
- int len = dataBytes.length / 2;
- char[] dataU8s = new char[len];
- byte high, low;
- for (int i = 0; i < len; i++) {
- high = dataBytes[i * 2];
- low = dataBytes[i * 2 + 1];
- dataU8s[i] = (char) (ByteUtil.combine2bytesToU16(high, low) + EXTRA_LEN);
- }
- return dataU8s;
- }
-}
diff --git a/android/app/src/main/java/cc/seeed/iot/esptouch/protocol/EsptouchGenerator.java b/android/app/src/main/java/cc/seeed/iot/esptouch/protocol/EsptouchGenerator.java
deleted file mode 100644
index 43cac3e..0000000
--- a/android/app/src/main/java/cc/seeed/iot/esptouch/protocol/EsptouchGenerator.java
+++ /dev/null
@@ -1,60 +0,0 @@
-package cc.seeed.iot.esptouch.protocol;
-
-import cc.seeed.iot.esptouch.task.IEsptouchGenerator;
-import cc.seeed.iot.esptouch.util.ByteUtil;
-
-import java.net.InetAddress;
-
-public class EsptouchGenerator implements IEsptouchGenerator {
-
- private final byte[][] mGcBytes2;
- private final byte[][] mDcBytes2;
-
- /**
- * Constructor of EsptouchGenerator, it will cost some time(maybe a bit
- * much)
- *
- * @param apSsid
- * the Ap's ssid
- * @param apBssid
- * the Ap's bssid
- * @param apPassword
- * the Ap's password
- * @param inetAddress
- * the phone's or pad's local ip address allocated by Ap
- * @param isSsidHidden
- * whether the Ap's ssid is hidden
- */
- public EsptouchGenerator(String apSsid, String apBssid, String apPassword,
- InetAddress inetAddress, boolean isSsidHiden) {
- // generate guide code
- GuideCode gc = new GuideCode();
- char[] gcU81 = gc.getU8s();
- mGcBytes2 = new byte[gcU81.length][];
-
- for (int i = 0; i < mGcBytes2.length; i++) {
- mGcBytes2[i] = ByteUtil.genSpecBytes(gcU81[i]);
- }
-
- // generate data code
- DatumCode dc = new DatumCode(apSsid, apBssid, apPassword, inetAddress,
- isSsidHiden);
- char[] dcU81 = dc.getU8s();
- mDcBytes2 = new byte[dcU81.length][];
-
- for (int i = 0; i < mDcBytes2.length; i++) {
- mDcBytes2[i] = ByteUtil.genSpecBytes(dcU81[i]);
- }
- }
-
- @Override
- public byte[][] getGCBytes2() {
- return mGcBytes2;
- }
-
- @Override
- public byte[][] getDCBytes2() {
- return mDcBytes2;
- }
-
-}
diff --git a/android/app/src/main/java/cc/seeed/iot/esptouch/protocol/GuideCode.java b/android/app/src/main/java/cc/seeed/iot/esptouch/protocol/GuideCode.java
deleted file mode 100644
index ee0a84e..0000000
--- a/android/app/src/main/java/cc/seeed/iot/esptouch/protocol/GuideCode.java
+++ /dev/null
@@ -1,39 +0,0 @@
-package cc.seeed.iot.esptouch.protocol;
-
-import cc.seeed.iot.esptouch.task.ICodeData;
-import cc.seeed.iot.esptouch.util.ByteUtil;
-
-public class GuideCode implements ICodeData {
-
- public static final int GUIDE_CODE_LEN = 4;
-
- @Override
- public byte[] getBytes() {
- throw new RuntimeException("DataCode don't support getBytes()");
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- char[] dataU8s = getU8s();
- for (int i = 0; i < GUIDE_CODE_LEN; i++) {
- String hexString = ByteUtil.convertU8ToHexString(dataU8s[i]);
- sb.append("0x");
- if (hexString.length() == 1) {
- sb.append("0");
- }
- sb.append(hexString).append(" ");
- }
- return sb.toString();
- }
-
- @Override
- public char[] getU8s() {
- char[] guidesU8s = new char[GUIDE_CODE_LEN];
- guidesU8s[0] = 515;
- guidesU8s[1] = 514;
- guidesU8s[2] = 513;
- guidesU8s[3] = 512;
- return guidesU8s;
- }
-}
diff --git a/android/app/src/main/java/cc/seeed/iot/esptouch/task/EsptouchTaskParameter.java b/android/app/src/main/java/cc/seeed/iot/esptouch/task/EsptouchTaskParameter.java
deleted file mode 100644
index 7c81f93..0000000
--- a/android/app/src/main/java/cc/seeed/iot/esptouch/task/EsptouchTaskParameter.java
+++ /dev/null
@@ -1,150 +0,0 @@
-package cc.seeed.iot.esptouch.task;
-
-public class EsptouchTaskParameter implements IEsptouchTaskParameter {
-
- private long mIntervalGuideCodeMillisecond;
- private long mIntervalDataCodeMillisecond;
- private long mTimeoutGuideCodeMillisecond;
- private long mTimeoutDataCodeMillisecond;
- private int mTotalRepeatTime;
- private int mEsptouchResultOneLen;
- private int mEsptouchResultMacLen;
- private int mEsptouchResultIpLen;
- private int mEsptouchResultTotalLen;
- private int mPortListening;
- private String mTargetHostname;
- private int mTargetPort;
- private int mWaitUdpReceivingMilliseond;
- private int mWaitUdpSendingMillisecond;
- private int mThresholdSucBroadcastCount;
- private int mExpectTaskResultCount;
-
- public EsptouchTaskParameter() {
- mIntervalGuideCodeMillisecond = 10;
- mIntervalDataCodeMillisecond = 10;
- mTimeoutGuideCodeMillisecond = 2000;
- mTimeoutDataCodeMillisecond = 4000;
- mTotalRepeatTime = 1;
- mEsptouchResultOneLen = 1;
- mEsptouchResultMacLen = 6;
- mEsptouchResultIpLen = 4;
- mEsptouchResultTotalLen = 1 + 6 + 4;
- mPortListening = 18266;
- mTargetHostname = "255.255.255.255";
- mTargetPort = 7001;
- mWaitUdpReceivingMilliseond = 10000;
- mWaitUdpSendingMillisecond = 48000;
- mThresholdSucBroadcastCount = 1;
- mExpectTaskResultCount = 1;
- }
-
- @Override
- public long getIntervalGuideCodeMillisecond() {
- return mIntervalGuideCodeMillisecond;
- }
-
- @Override
- public long getIntervalDataCodeMillisecond() {
- return mIntervalDataCodeMillisecond;
- }
-
- @Override
- public long getTimeoutGuideCodeMillisecond() {
- return mTimeoutGuideCodeMillisecond;
- }
-
- @Override
- public long getTimeoutDataCodeMillisecond() {
- return mTimeoutDataCodeMillisecond;
- }
-
- @Override
- public long getTimeoutTotalCodeMillisecond() {
- return mTimeoutGuideCodeMillisecond + mTimeoutDataCodeMillisecond;
- }
-
- @Override
- public int getTotalRepeatTime() {
- return mTotalRepeatTime;
- }
-
- @Override
- public int getEsptouchResultOneLen() {
- return mEsptouchResultOneLen;
- }
-
- @Override
- public int getEsptouchResultMacLen() {
- return mEsptouchResultMacLen;
- }
-
- @Override
- public int getEsptouchResultIpLen() {
- return mEsptouchResultIpLen;
- }
-
- @Override
- public int getEsptouchResultTotalLen() {
- return mEsptouchResultTotalLen;
- }
-
- @Override
- public int getPortListening() {
- return mPortListening;
- }
-
- @Override
- public String getTargetHostname() {
- return mTargetHostname;
- }
-
- @Override
- public int getTargetPort() {
- return mTargetPort;
- }
-
- @Override
- public int getWaitUdpReceivingMillisecond() {
- return mWaitUdpReceivingMilliseond;
- }
-
- @Override
- public int getWaitUdpSendingMillisecond() {
- return mWaitUdpSendingMillisecond;
- }
-
- @Override
- public int getWaitUdpTotalMillisecond() {
- return mWaitUdpReceivingMilliseond + mWaitUdpSendingMillisecond;
- }
-
- @Override
- public int getThresholdSucBroadcastCount() {
- return mThresholdSucBroadcastCount;
- }
-
- @Override
- public void setWaitUdpTotalMillisecond(int waitUdpTotalMillisecond) {
- if (waitUdpTotalMillisecond < mWaitUdpReceivingMilliseond
- + getTimeoutTotalCodeMillisecond()) {
- // if it happen, even one turn about sending udp broadcast can't be
- // completed
- throw new IllegalArgumentException(
- "waitUdpTotalMillisecod is invalid, "
- + "it is less than mWaitUdpReceivingMilliseond + getTimeoutTotalCodeMillisecond()");
- }
- mWaitUdpSendingMillisecond = waitUdpTotalMillisecond
- - mWaitUdpReceivingMilliseond;
- }
-
- @Override
- public int getExpectTaskResultCount() {
- return this.mExpectTaskResultCount;
- }
-
- @Override
- public void setExpectTaskResultCount(int expectTaskResultCount) {
- this.mExpectTaskResultCount = expectTaskResultCount;
- }
-
-}
diff --git a/android/app/src/main/java/cc/seeed/iot/esptouch/task/ICodeData.java b/android/app/src/main/java/cc/seeed/iot/esptouch/task/ICodeData.java
deleted file mode 100644
index b8074bd..0000000
--- a/android/app/src/main/java/cc/seeed/iot/esptouch/task/ICodeData.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package cc.seeed.iot.esptouch.task;
-
-/**
- * the class used to represent some code to be transformed by UDP socket should implement the interface
- * @author afunx
- *
- */
-public interface ICodeData {
- /**
- * Get the byte[] to be transformed.
- *
- *
- * @return the byte[] to be transfromed
- */
- byte[] getBytes();
-
- /**
- * Get the char[](u8[]) to be transfromed.
- *
- * @return the char[](u8) to be transformed
- */
- char[] getU8s();
-}
diff --git a/android/app/src/main/java/cc/seeed/iot/esptouch/task/IEsptouchGenerator.java b/android/app/src/main/java/cc/seeed/iot/esptouch/task/IEsptouchGenerator.java
deleted file mode 100644
index d2e8e24..0000000
--- a/android/app/src/main/java/cc/seeed/iot/esptouch/task/IEsptouchGenerator.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package cc.seeed.iot.esptouch.task;
-
-public interface IEsptouchGenerator {
- /**
- * Get guide code by the format of byte[][]
- *
- * @return guide code by the format of byte[][]
- */
- byte[][] getGCBytes2();
-
- /**
- * Get data code by the format of byte[][]
- *
- * @return data code by the format of byte[][]
- */
- byte[][] getDCBytes2();
-}
diff --git a/android/app/src/main/java/cc/seeed/iot/esptouch/task/IEsptouchTaskParameter.java b/android/app/src/main/java/cc/seeed/iot/esptouch/task/IEsptouchTaskParameter.java
deleted file mode 100644
index e2e60dc..0000000
--- a/android/app/src/main/java/cc/seeed/iot/esptouch/task/IEsptouchTaskParameter.java
+++ /dev/null
@@ -1,129 +0,0 @@
-package cc.seeed.iot.esptouch.task;
-
-public interface IEsptouchTaskParameter {
-
- /**
- * get interval millisecond for guide code(the time between each guide code sending)
- * @return interval millisecond for guide code(the time between each guide code sending)
- */
- long getIntervalGuideCodeMillisecond();
-
- /**
- * get interval millisecond for data code(the time between each data code sending)
- * @return interval millisecond for data code(the time between each data code sending)
- */
- long getIntervalDataCodeMillisecond();
-
- /**
- * get timeout millisecond for guide code(the time how much the guide code sending)
- * @return timeout millisecond for guide code(the time how much the guide code sending)
- */
- long getTimeoutGuideCodeMillisecond();
-
- /**
- * get timeout millisecond for data code(the time how much the data code sending)
- * @return timeout millisecond for data code(the time how much the data code sending)
- */
- long getTimeoutDataCodeMillisecond();
-
- /**
- * get timeout millisecond for total code(guide code and data code altogether)
- * @return timeout millisecond for total code(guide code and data code altogether)
- */
- long getTimeoutTotalCodeMillisecond();
-
- /**
- * get total repeat time for executing esptouch task
- * @return total repeat time for executing esptouch task
- */
- int getTotalRepeatTime();
-
- /**
- * the length of the Esptouch result 1st byte is the total length of ssid and
- * password, the other 6 bytes are the device's bssid
- */
-
- /**
- * get esptouchResult length of one
- * @return length of one
- */
- int getEsptouchResultOneLen();
-
- /**
- * get esptouchResult length of mac
- * @return length of mac
- */
- int getEsptouchResultMacLen();
-
- /**
- * get esptouchResult length of ip
- * @return length of ip
- */
- int getEsptouchResultIpLen();
-
- /**
- * get esptouchResult total length
- * @return total length
- */
- int getEsptouchResultTotalLen();
-
- /**
- * get port for listening(used by server)
- * @return port for listening(used by server)
- */
- int getPortListening();
-
- /**
- * get target hostname
- * @return target hostame(used by client)
- */
- String getTargetHostname();
-
- /**
- * get target port
- * @return target port(used by client)
- */
- int getTargetPort();
-
- /**
- * get millisecond for waiting udp receiving(receiving without sending)
- * @return millisecond for waiting udp receiving(receiving without sending)
- */
- int getWaitUdpReceivingMillisecond();
-
- /**
- * get millisecond for waiting udp sending(sending including receiving)
- * @return millisecond for waiting udep sending(sending including receiving)
- */
- int getWaitUdpSendingMillisecond();
-
- /**
- * get millisecond for waiting udp sending and receiving
- * @return millisecond for waiting udp sending and receiving
- */
- int getWaitUdpTotalMillisecond();
-
- /**
- * get the threshold for how many correct broadcast should be received
- * @return the threshold for how many correct broadcast should be received
- */
- int getThresholdSucBroadcastCount();
-
- /**
- * set the millisecond for waiting udp sending and receiving
- * @param waitUdpTotalMillisecond the millisecond for waiting udp sending and receiving
- */
- void setWaitUdpTotalMillisecond(int waitUdpTotalMillisecond);
-
- /**
- * get the count of expect task results
- * @return the count of expect task results
- */
- int getExpectTaskResultCount();
-
- /**
- * set the count of expect task results
- * @param expectTaskResultCount the count of expect task results
- */
- void setExpectTaskResultCount(int expectTaskResultCount);
-}
diff --git a/android/app/src/main/java/cc/seeed/iot/esptouch/task/__EsptouchTask.java b/android/app/src/main/java/cc/seeed/iot/esptouch/task/__EsptouchTask.java
deleted file mode 100644
index 07c3cf7..0000000
--- a/android/app/src/main/java/cc/seeed/iot/esptouch/task/__EsptouchTask.java
+++ /dev/null
@@ -1,338 +0,0 @@
-package cc.seeed.iot.esptouch.task;
-
-import android.content.Context;
-import android.os.Looper;
-import android.text.TextUtils;
-import android.util.Log;
-
-import cc.seeed.iot.esptouch.EsptouchResult;
-import cc.seeed.iot.esptouch.IEsptouchResult;
-import cc.seeed.iot.esptouch.protocol.EsptouchGenerator;
-import cc.seeed.iot.esptouch.udp.UDPSocketClient;
-import cc.seeed.iot.esptouch.udp.UDPSocketServer;
-import cc.seeed.iot.esptouch.util.ByteUtil;
-import cc.seeed.iot.esptouch.util.EspNetUtil;
-
-import java.net.InetAddress;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-public class __EsptouchTask implements __IEsptouchTask {
-
- /**
- * one indivisible data contain 3 9bits info
- */
- private static final int ONE_DATA_LEN = 3;
-
- private static final String TAG = "EsptouchTask";
-
- private volatile List mEsptouchResultList;
- private volatile boolean mIsSuc = false;
- private volatile boolean mIsInterrupt = false;
- private volatile boolean mIsExecuted = false;
- private final UDPSocketClient mSocketClient;
- private final UDPSocketServer mSocketServer;
- private final String mApSsid;
- private final String mApBssid;
- private final boolean mIsSsidHidden;
- private final String mApPassword;
- private final Context mContext;
- private AtomicBoolean mIsCancelled;
- private IEsptouchTaskParameter mParameter;
- private volatile Map mBssidTaskSucCountMap;
-
- public __EsptouchTask(String apSsid, String apBssid, String apPassword, Context context, IEsptouchTaskParameter parameter
- ,boolean isSsidHidden) {
- if (TextUtils.isEmpty(apSsid)) {
- throw new IllegalArgumentException(
- "the apSsid should be null or empty");
- }
- if (apPassword == null) {
- apPassword = "";
- }
- mContext = context;
- mApSsid = apSsid;
- mApBssid = apBssid;
- mApPassword = apPassword;
- mIsCancelled = new AtomicBoolean(false);
- mSocketClient = new UDPSocketClient();
- mParameter = parameter;
- mSocketServer = new UDPSocketServer(mParameter.getPortListening(),
- mParameter.getWaitUdpTotalMillisecond(),
- context);
- mIsSsidHidden = isSsidHidden;
- mEsptouchResultList = new ArrayList();
- mBssidTaskSucCountMap = new HashMap();
- }
-
- private void __putEsptouchResult(boolean isSuc, String bssid,
- InetAddress inetAddress) {
- synchronized (mEsptouchResultList) {
- // check whether the result receive enough UDP response
- boolean isTaskSucCountEnough = false;
- Integer count = mBssidTaskSucCountMap.get(bssid);
- if (count == null) {
- count = 0;
- }
- ++count;
- if (DEBUG) {
- Log.d(TAG, "__putEsptouchResult(): count = " + count);
- }
- mBssidTaskSucCountMap.put(bssid, count);
- isTaskSucCountEnough = count >= mParameter
- .getThresholdSucBroadcastCount();
- if (!isTaskSucCountEnough) {
- if (DEBUG) {
- Log.d(TAG, "__putEsptouchResult(): count = " + count
- + ", isn't enough");
- }
- return;
- }
- // check whether the result is in the mEsptouchResultList already
- boolean isExist = false;
- for (IEsptouchResult esptouchResultInList : mEsptouchResultList) {
- if (esptouchResultInList.getBssid().equals(bssid)) {
- isExist = true;
- break;
- }
- }
- // only add the result who isn't in the mEsptouchResultList
- if (!isExist) {
- if (DEBUG) {
- Log.d(TAG, "__putEsptouchResult(): put one more result");
- }
- IEsptouchResult esptouchResult = new EsptouchResult(isSuc,
- bssid, inetAddress);
- mEsptouchResultList.add(esptouchResult);
- }
- }
- }
-
- private List __getEsptouchResultList() {
- synchronized (mEsptouchResultList) {
- if (mEsptouchResultList.isEmpty()) {
- EsptouchResult esptouchResultFail = new EsptouchResult(false,
- null, null);
- esptouchResultFail.setIsCancelled(mIsCancelled.get());
- mEsptouchResultList.add(esptouchResultFail);
- }
- return mEsptouchResultList;
- }
- }
-
- private synchronized void __interrupt() {
- if (!mIsInterrupt) {
- mIsInterrupt = true;
- mSocketClient.interrupt();
- mSocketServer.interrupt();
- // interrupt the current Thread which is used to wait for udp response
- Thread.currentThread().interrupt();
- }
- }
-
- @Override
- public void interrupt() {
- if (DEBUG) {
- Log.d(TAG, "interrupt()");
- }
- mIsCancelled.set(true);
- __interrupt();
- }
-
- private void __listenAsyn(final int expectDataLen) {
- new Thread() {
- public void run() {
- if (DEBUG) {
- Log.d(TAG, "__listenAsyn() start");
- }
- long startTimestamp = System.currentTimeMillis();
- byte[] apSsidAndPassword = ByteUtil.getBytesByString(mApSsid
- + mApPassword);
- byte expectOneByte = (byte) (apSsidAndPassword.length + 9);
- if (DEBUG) {
- Log.i(TAG, "expectOneByte: " + (0 + expectOneByte));
- }
- byte receiveOneByte = -1;
- byte[] receiveBytes = null;
- while (mEsptouchResultList.size() < mParameter
- .getExpectTaskResultCount() && !mIsInterrupt) {
- receiveBytes = mSocketServer
- .receiveSpecLenBytes(expectDataLen);
- if (receiveBytes != null) {
- receiveOneByte = receiveBytes[0];
- } else {
- receiveOneByte = -1;
- }
- if (receiveOneByte == expectOneByte) {
- if (DEBUG) {
- Log.i(TAG, "receive correct broadcast");
- }
- // change the socket's timeout
- long consume = System.currentTimeMillis()
- - startTimestamp;
- int timeout = (int) (mParameter
- .getWaitUdpTotalMillisecond() - consume);
- if (timeout < 0) {
- if (DEBUG) {
- Log.i(TAG, "esptouch timeout");
- }
- break;
- } else {
- if (DEBUG) {
- Log.i(TAG, "mSocketServer's new timeout is "
- + timeout + " milliseconds");
- }
- mSocketServer.setSoTimeout(timeout);
- if (DEBUG) {
- Log.i(TAG, "receive correct broadcast");
- }
- if (receiveBytes != null) {
- String bssid = ByteUtil.parseBssid(
- receiveBytes,
- mParameter.getEsptouchResultOneLen(),
- mParameter.getEsptouchResultMacLen());
- InetAddress inetAddress = EspNetUtil
- .parseInetAddr(
- receiveBytes,
- mParameter.getEsptouchResultOneLen()
- + mParameter.getEsptouchResultMacLen(),
- mParameter.getEsptouchResultIpLen());
- __putEsptouchResult(true, bssid, inetAddress);
- }
- }
- } else {
- if (DEBUG) {
- Log.i(TAG, "receive rubbish message, just ignore");
- }
- }
- }
- mIsSuc = mEsptouchResultList.size() >= mParameter
- .getExpectTaskResultCount();
- __EsptouchTask.this.__interrupt();
- if (DEBUG) {
- Log.d(TAG, "__listenAsyn() finish");
- }
- }
- }.start();
- }
-
- private boolean __execute(IEsptouchGenerator generator) {
-
- long startTime = System.currentTimeMillis();
- long currentTime = startTime;
- long lastTime = currentTime - mParameter.getTimeoutTotalCodeMillisecond();
-
- byte[][] gcBytes2 = generator.getGCBytes2();
- byte[][] dcBytes2 = generator.getDCBytes2();
-
- int index = 0;
- while (!mIsInterrupt) {
- if (currentTime - lastTime >= mParameter.getTimeoutTotalCodeMillisecond()) {
- if (DEBUG) {
- Log.d(TAG, "send gc code ");
- }
- // send guide code
- while (!mIsInterrupt
- && System.currentTimeMillis() - currentTime < mParameter
- .getTimeoutGuideCodeMillisecond()) {
- mSocketClient.sendData(gcBytes2,
- mParameter.getTargetHostname(),
- mParameter.getTargetPort(),
- mParameter.getIntervalGuideCodeMillisecond());
- // check whether the udp is send enough time
- if (System.currentTimeMillis() - startTime > mParameter.getWaitUdpSendingMillisecond()) {
- break;
- }
- }
- lastTime = currentTime;
- } else {
- mSocketClient.sendData(dcBytes2, index, ONE_DATA_LEN,
- mParameter.getTargetHostname(),
- mParameter.getTargetPort(),
- mParameter.getIntervalDataCodeMillisecond());
- index = (index + ONE_DATA_LEN) % dcBytes2.length;
- }
- currentTime = System.currentTimeMillis();
- // check whether the udp is send enough time
- if (currentTime - startTime > mParameter.getWaitUdpSendingMillisecond()) {
- break;
- }
- }
-
- return mIsSuc;
- }
-
- private void __checkTaskValid() {
- // !!!NOTE: the esptouch task could be executed only once
- if (this.mIsExecuted) {
- throw new IllegalStateException(
- "the Esptouch task could be executed only once");
- }
- this.mIsExecuted = true;
- }
-
- @Override
- public IEsptouchResult executeForResult() throws RuntimeException {
- return executeForResults(1).get(0);
- }
-
- @Override
- public boolean isCancelled() {
- return this.mIsCancelled.get();
- }
-
- @Override
- public List executeForResults(int expectTaskResultCount)
- throws RuntimeException {
- __checkTaskValid();
-
- mParameter.setExpectTaskResultCount(expectTaskResultCount);
-
- if (DEBUG) {
- Log.d(TAG, "execute()");
- }
- if (Looper.myLooper() == Looper.getMainLooper()) {
- throw new RuntimeException(
- "Don't call the esptouch Task at Main(UI) thread directly.");
- }
- InetAddress localInetAddress = EspNetUtil.getLocalInetAddress(mContext);
- if (DEBUG) {
- Log.i(TAG, "localInetAddress: " + localInetAddress);
- }
- // generator the esptouch byte[][] to be transformed, which will cost
- // some time(maybe a bit much)
- IEsptouchGenerator generator = new EsptouchGenerator(mApSsid, mApBssid,
- mApPassword, localInetAddress, mIsSsidHidden);
- // listen the esptouch result asyn
- __listenAsyn(mParameter.getEsptouchResultTotalLen());
- boolean isSuc = false;
- for (int i = 0; i < mParameter.getTotalRepeatTime(); i++) {
- isSuc = __execute(generator);
- if (isSuc) {
- return __getEsptouchResultList();
- }
- }
-
- // wait the udp response without sending udp broadcast
- try {
- Thread.sleep(mParameter.getWaitUdpReceivingMillisecond());
- } catch (InterruptedException e) {
- // receive the udp broadcast or the user interrupt the task
- if (this.mIsSuc)
- {
- return __getEsptouchResultList();
- }
- else
- {
- this.__interrupt();
- return __getEsptouchResultList();
- }
- }
- this.__interrupt();
- return __getEsptouchResultList();
- }
-
-}
diff --git a/android/app/src/main/java/cc/seeed/iot/esptouch/task/__IEsptouchTask.java b/android/app/src/main/java/cc/seeed/iot/esptouch/task/__IEsptouchTask.java
deleted file mode 100644
index a9d46e5..0000000
--- a/android/app/src/main/java/cc/seeed/iot/esptouch/task/__IEsptouchTask.java
+++ /dev/null
@@ -1,49 +0,0 @@
-package cc.seeed.iot.esptouch.task;
-
-import cc.seeed.iot.esptouch.IEsptouchResult;
-
-import java.util.List;
-
-/**
- * IEsptouchTask defined the task of esptouch should offer. INTERVAL here means
- * the milliseconds of interval of the step. REPEAT here means the repeat times
- * of the step.
- *
- * @author afunx
- *
- */
-public interface __IEsptouchTask {
-
- /**
- * Interrupt the Esptouch Task when User tap back or close the Application.
- */
- void interrupt();
-
- /**
- * Note: !!!Don't call the task at UI Main Thread or RuntimeException will
- * be thrown Execute the Esptouch Task and return the result
- *
- * @return the IEsptouchResult
- * @throws RuntimeException
- */
- IEsptouchResult executeForResult() throws RuntimeException;
-
- /**
- * Note: !!!Don't call the task at UI Main Thread or RuntimeException will
- * be thrown Execute the Esptouch Task and return the result
- *
- * @param expectTaskResultCount
- * the expect result count(if expectTaskResultCount <= 0,
- * expectTaskResultCount = Integer.MAX_VALUE)
- * @return the list of IEsptouchResult
- * @throws RuntimeException
- */
- List executeForResults(int expectTaskResultCount) throws RuntimeException;
-
- /**
- * Turn on or off the log.
- */
- static final boolean DEBUG = true;
-
- boolean isCancelled();
-}
diff --git a/android/app/src/main/java/cc/seeed/iot/esptouch/udp/UDPSocketClient.java b/android/app/src/main/java/cc/seeed/iot/esptouch/udp/UDPSocketClient.java
deleted file mode 100644
index cf05246..0000000
--- a/android/app/src/main/java/cc/seeed/iot/esptouch/udp/UDPSocketClient.java
+++ /dev/null
@@ -1,144 +0,0 @@
-package cc.seeed.iot.esptouch.udp;
-
-import android.util.Log;
-
-import cc.seeed.iot.esptouch.task.__IEsptouchTask;
-
-import java.io.IOException;
-import java.net.DatagramPacket;
-import java.net.DatagramSocket;
-import java.net.InetAddress;
-import java.net.SocketException;
-import java.net.UnknownHostException;
-
-/**
- * this class is used to help send UDP data according to length
- *
- * @author afunx
- *
- */
-public class UDPSocketClient {
-
- private static final String TAG = "UDPSocketClient";
- private DatagramSocket mSocket;
- private volatile boolean mIsStop;
- private volatile boolean mIsClosed;
-
- public UDPSocketClient() {
- try {
- this.mSocket = new DatagramSocket();
- this.mIsStop = false;
- this.mIsClosed = false;
- } catch (SocketException e) {
- if (__IEsptouchTask.DEBUG) {
- Log.e(TAG, "SocketException");
- }
- e.printStackTrace();
- }
- }
-
- @Override
- protected void finalize() throws Throwable {
- close();
- super.finalize();
- }
-
- public void interrupt() {
- if (__IEsptouchTask.DEBUG) {
- Log.i(TAG, "USPSocketClient is interrupt");
- }
- this.mIsStop = true;
- }
-
- /**
- * close the UDP socket
- */
- public synchronized void close() {
- if (!this.mIsClosed) {
- this.mSocket.close();
- this.mIsClosed = true;
- }
- }
-
- /**
- * send the data by UDP
- *
- * @param data
- * the data to be sent
- * @param targetHost
- * the host name of target, e.g. 192.168.1.101
- * @param targetPort
- * the port of target
- * @param interval
- * the milliseconds to between each UDP sent
- */
- public void sendData(byte[][] data, String targetHostName, int targetPort,
- long interval) {
- sendData(data, 0, data.length, targetHostName, targetPort, interval);
- }
-
-
- /**
- * send the data by UDP
- *
- * @param data
- * the data to be sent
- * @param offset
- * the offset which data to be sent
- * @param count
- * the count of the data
- * @param targetHost
- * the host name of target, e.g. 192.168.1.101
- * @param targetPort
- * the port of target
- * @param interval
- * the milliseconds to between each UDP sent
- */
- public void sendData(byte[][] data, int offset, int count,
- String targetHostName, int targetPort, long interval) {
- if ((data == null) || (data.length <= 0)) {
- if (__IEsptouchTask.DEBUG) {
- Log.e(TAG, "sendData(): data == null or length <= 0");
- }
- return;
- }
- for (int i = offset; !mIsStop && i < offset + count; i++) {
- if (data[i].length == 0) {
- continue;
- }
- try {
- // Log.i(TAG, "data[" + i + " +].length = " + data[i].length);
- DatagramPacket localDatagramPacket = new DatagramPacket(
- data[i], data[i].length,
- InetAddress.getByName(targetHostName), targetPort);
- this.mSocket.send(localDatagramPacket);
- } catch (UnknownHostException e) {
- if (__IEsptouchTask.DEBUG) {
- Log.e(TAG, "sendData(): UnknownHostException");
- }
- e.printStackTrace();
- mIsStop = true;
- break;
- } catch (IOException e) {
- if (__IEsptouchTask.DEBUG) {
- Log.e(TAG, "sendData(): IOException, but just ignore it");
- }
- // for the Ap will make some troubles when the phone send too many UDP packets,
- // but we don't expect the UDP packet received by others, so just ignore it
- }
- try {
- Thread.sleep(interval);
- } catch (InterruptedException e) {
- e.printStackTrace();
- if (__IEsptouchTask.DEBUG) {
- Log.e(TAG, "sendData is Interrupted");
- }
- mIsStop = true;
- break;
- }
- }
- if (mIsStop) {
- close();
- }
- }
-}
diff --git a/android/app/src/main/java/cc/seeed/iot/esptouch/udp/UDPSocketServer.java b/android/app/src/main/java/cc/seeed/iot/esptouch/udp/UDPSocketServer.java
deleted file mode 100644
index ae20d3e..0000000
--- a/android/app/src/main/java/cc/seeed/iot/esptouch/udp/UDPSocketServer.java
+++ /dev/null
@@ -1,152 +0,0 @@
-package cc.seeed.iot.esptouch.udp;
-
-import android.content.Context;
-import android.net.wifi.WifiManager;
-import android.util.Log;
-
-import java.io.IOException;
-import java.net.DatagramPacket;
-import java.net.DatagramSocket;
-import java.net.SocketException;
-import java.util.Arrays;
-
-public class UDPSocketServer {
-
- private static final String TAG = "UDPSocketServer";
- private DatagramPacket mReceivePacket;
- private DatagramSocket mServerSocket;
- private Context mContext;
- private WifiManager.MulticastLock mLock;
- private final byte[] buffer;
- private volatile boolean mIsClosed;
-
- private synchronized void acquireLock() {
- if (mLock != null && !mLock.isHeld()) {
- mLock.acquire();
- }
- }
-
- private synchronized void releaseLock() {
- if (mLock != null && mLock.isHeld()) {
- try {
- mLock.release();
- } catch (Throwable th) {
- // ignoring this exception, probably wakeLock was already released
- }
- }
- }
-
- /**
- * Constructor of UDP Socket Server
- *
- * @param port
- * the Socket Server port
- * @param socketTimeout
- * the socket read timeout
- * @param context
- * the context of the Application
- */
- public UDPSocketServer(int port, int socketTimeout, Context context) {
- this.mContext = context;
- this.buffer = new byte[64];
- this.mReceivePacket = new DatagramPacket(buffer, 64);
- try {
- this.mServerSocket = new DatagramSocket(port);
- this.mServerSocket.setSoTimeout(socketTimeout);
- this.mIsClosed = false;
- WifiManager manager = (WifiManager) mContext
- .getSystemService(Context.WIFI_SERVICE);
- mLock = manager.createMulticastLock("test wifi");
- Log.d(TAG, "mServerSocket is created, socket read timeout: "
- + socketTimeout + ", port: " + port);
- } catch (IOException e) {
- Log.e(TAG, "IOException");
- e.printStackTrace();
- }
- }
-
- /**
- * Set the socket timeout in milliseconds
- *
- * @param timeout
- * the timeout in milliseconds or 0 for no timeout.
- * @return true whether the timeout is set suc
- */
- public boolean setSoTimeout(int timeout) {
- try {
- this.mServerSocket.setSoTimeout(timeout);
- return true;
- } catch (SocketException e) {
- e.printStackTrace();
- }
- return false;
- }
-
- /**
- * Receive one byte from the port and convert it into String
- *
- * @return
- */
- public byte receiveOneByte() {
- Log.d(TAG, "receiveOneByte() entrance");
- try {
- acquireLock();
- mServerSocket.receive(mReceivePacket);
- Log.d(TAG, "receive: " + (0 + mReceivePacket.getData()[0]));
- return mReceivePacket.getData()[0];
- } catch (IOException e) {
- e.printStackTrace();
- }
- return Byte.MIN_VALUE;
- }
-
- /**
- * Receive specific length bytes from the port and convert it into String
- * 21,24,-2,52,-102,-93,-60
- * 15,18,fe,34,9a,a3,c4
- * @return
- */
- public byte[] receiveSpecLenBytes(int len) {
- Log.d(TAG, "receiveSpecLenBytes() entrance: len = " + len);
- try {
- acquireLock();
- mServerSocket.receive(mReceivePacket);
- byte[] recDatas = Arrays.copyOf(mReceivePacket.getData(), mReceivePacket.getLength());
- Log.d(TAG, "received len : " + recDatas.length);
- for (int i = 0; i < recDatas.length; i++) {
- Log.e(TAG, "recDatas[" + i + "]:" + recDatas[i]);
- }
- Log.e(TAG, "receiveSpecLenBytes: " + new String(recDatas));
- if (recDatas.length != len) {
- Log.w(TAG,
- "received len is different from specific len, return null");
- return null;
- }
- return recDatas;
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
-
- public void interrupt() {
- Log.i(TAG, "USPSocketServer is interrupt");
- close();
- }
-
- public synchronized void close() {
- if (!this.mIsClosed) {
- Log.e(TAG, "mServerSocket is closed");
- mServerSocket.close();
- releaseLock();
- this.mIsClosed = true;
- }
- }
-
- @Override
- protected void finalize() throws Throwable {
- close();
- super.finalize();
- }
-
-}
diff --git a/android/app/src/main/java/cc/seeed/iot/esptouch/util/ByteUtil.java b/android/app/src/main/java/cc/seeed/iot/esptouch/util/ByteUtil.java
deleted file mode 100644
index 5b578b5..0000000
--- a/android/app/src/main/java/cc/seeed/iot/esptouch/util/ByteUtil.java
+++ /dev/null
@@ -1,351 +0,0 @@
-package cc.seeed.iot.esptouch.util;
-
-import java.io.UnsupportedEncodingException;
-import java.util.Random;
-
-/**
- * In Java, it don't support unsigned int, so we use char to replace uint8.
- * The range of byte is [-128,127], and the range of char is [0,65535].
- * So the byte could used to store the uint8.
- * (We assume that the String could be mapped to assic)
- * @author afunx
- *
- */
-public class ByteUtil {
-
- public static final String ESPTOUCH_ENCODING_CHARSET = "UTF-8";
-
- /**
- * Put String to byte[]
- *
- * @param destbytes
- * the byte[] of dest
- * @param srcString
- * the String of src
- * @param destOffset
- * the offset of byte[]
- * @param srcOffset
- * the offset of String
- * @param count
- * the count of dest, and the count of src as well
- */
- public static void putString2bytes(byte[] destbytes, String srcString,
- int destOffset, int srcOffset, int count) {
- for (int i = 0; i < count; i++) {
- destbytes[count + i] = srcString.getBytes()[i];
- }
- }
-
- /**
- * Convert uint8 into char( we treat char as uint8)
- *
- * @param uint8
- * the unit8 to be converted
- * @return the byte of the unint8
- */
- public static byte convertUint8toByte(char uint8) {
- if (uint8 > Byte.MAX_VALUE - Byte.MIN_VALUE) {
- throw new RuntimeException("Out of Boundary");
- }
- return (byte) uint8;
- }
-
- /**
- * Convert char into uint8( we treat char as uint8 )
- *
- * @param b
- * the byte to be converted
- * @return the char(uint8)
- */
- public static char convertByte2Uint8(byte b) {
- // char will be promoted to int for char don't support & operator
- // & 0xff could make negatvie value to positive
- return (char) (b & 0xff);
- }
-
- /**
- * Convert byte[] into char[]( we treat char[] as uint8[])
- *
- * @param bytes
- * the byte[] to be converted
- * @return the char[](uint8[])
- */
- public static char[] convertBytes2Uint8s(byte[] bytes) {
- int len = bytes.length;
- char[] uint8s = new char[len];
- for (int i = 0; i < len; i++) {
- uint8s[i] = convertByte2Uint8(bytes[i]);
- }
- return uint8s;
- }
-
- /**
- * Put byte[] into char[]( we treat char[] as uint8[])
- *
- * @param dest
- * the char[](uint8[]) array
- * @param src
- * the byte[]
- * @param destOffset
- * the offset of char[](uint8[])
- * @param srcOffset
- * the offset of byte[]
- * @param count
- * the count of dest, and the count of src as well
- */
- public static void putbytes2Uint8s(char[] destUint8s, byte[] srcBytes,
- int destOffset, int srcOffset, int count) {
- for (int i = 0; i < count; i++) {
- destUint8s[destOffset + i] = convertByte2Uint8(srcBytes[srcOffset
- + i]);
- }
- }
-
- /**
- * Convert byte to Hex String
- *
- * @param b
- * the byte to be converted
- * @return the Hex String
- */
- public static String convertByte2HexString(byte b) {
- char u8 = convertByte2Uint8(b);
- return Integer.toHexString(u8);
- }
-
- /**
- * Convert char(uint8) to Hex String
- *
- * @param u8
- * the char(uint8) to be converted
- * @return the Hex String
- */
- public static String convertU8ToHexString(char u8) {
- return Integer.toHexString(u8);
- }
-
- /**
- * Split uint8 to 2 bytes of high byte and low byte. e.g. 20 = 0x14 should
- * be split to [0x01,0x04] 0x01 is high byte and 0x04 is low byte
- *
- * @param uint8
- * the char(uint8)
- * @return the high and low bytes be split, byte[0] is high and byte[1] is
- * low
- */
- public static byte[] splitUint8To2bytes(char uint8) {
- if (uint8 < 0 || uint8 > 0xff) {
- throw new RuntimeException("Out of Boundary");
- }
- String hexString = Integer.toHexString(uint8);
- byte low;
- byte high;
- if (hexString.length() > 1) {
- high = (byte) Integer.parseInt(hexString.substring(0, 1), 16);
- low = (byte) Integer.parseInt(hexString.substring(1, 2), 16);
- } else {
- high = 0;
- low = (byte) Integer.parseInt(hexString.substring(0, 1), 16);
- }
- byte[] result = new byte[] { high, low };
- return result;
- }
-
- /**
- * Combine 2 bytes (high byte and low byte) to one whole byte
- *
- * @param high
- * the high byte
- * @param low
- * the low byte
- * @return the whole byte
- */
- public static byte combine2bytesToOne(byte high, byte low) {
- if (high < 0 || high > 0xf || low < 0 || low > 0xf) {
- throw new RuntimeException("Out of Boundary");
- }
- return (byte) (high << 4 | low);
- }
-
- /**
- * Combine 2 bytes (high byte and low byte) to
- *
- * @param high
- * the high byte
- * @param low
- * the low byte
- * @return the char(u8)
- */
- public static char combine2bytesToU16(byte high, byte low) {
- char highU8 = convertByte2Uint8(high);
- char lowU8 = convertByte2Uint8(low);
- return (char) (highU8 << 8 | lowU8);
- }
-
- /**
- * Generate the random byte to be sent
- *
- * @return the random byte
- */
- private static byte randomByte() {
- return (byte) (127 - new Random().nextInt(256));
- }
-
- /**
- * Generate the random byte to be sent
- *
- * @param len
- * the len presented by u8
- * @return the byte[] to be sent
- */
- public static byte[] randomBytes(char len) {
- byte[] data = new byte[len];
- for (int i = 0; i < len; i++) {
- data[i] = randomByte();
- }
- return data;
- }
-
- public static byte[] genSpecBytes(char len) {
- byte[] data = new byte[len];
- for (int i = 0; i < len; i++) {
- data[i] = '1';
- }
- return data;
- }
-
- /**
- * Generate the random byte to be sent
- *
- * @param len
- * the len presented by byte
- * @return the byte[] to be sent
- */
- public static byte[] randomBytes(byte len) {
- char u8 = convertByte2Uint8(len);
- return randomBytes(u8);
- }
-
- /**
- * Generate the specific byte to be sent
- * @param len
- * the len presented by byte
- * @return the byte[]
- */
- public static byte[] genSpecBytes(byte len) {
- char u8 = convertByte2Uint8(len);
- return genSpecBytes(u8);
- }
-
- public static String parseBssid(byte[] bssidBytes, int offset, int count) {
- byte[] bytes = new byte[count];
- for (int i = 0; i < count; i++) {
- bytes[i] = bssidBytes[i + offset];
- }
- return parseBssid(bytes);
- }
-
- /**
- * parse "24,-2,52,-102,-93,-60" to "18,fe,34,9a,a3,c4"
- * parse the bssid from hex to String
- * @param bssidBytes the hex bytes bssid, e.g. {24,-2,52,-102,-93,-60}
- * @return the String of bssid, e.g. 18fe349aa3c4
- */
- public static String parseBssid(byte[] bssidBytes)
- {
- StringBuilder sb = new StringBuilder();
- int k;
- String hexK;
- String str;
- for (int i = 0; i < bssidBytes.length; i++)
- {
- k = 0xff & bssidBytes[i];
- hexK = Integer.toHexString(k);
- str = ((k < 16) ? ("0" + hexK) : (hexK));
- System.out.println(str);
- sb.append(str);
- }
- return sb.toString();
- }
-
- /**
- * @param string the string to be used
- * @return the byte[] of String according to {@link #ESPTOUCH_ENCODING_CHARSET}
- */
- public static byte[] getBytesByString(String string) {
- try {
- return string.getBytes(ESPTOUCH_ENCODING_CHARSET);
- } catch (UnsupportedEncodingException e) {
- throw new IllegalArgumentException("the charset is invalid");
- }
- }
-
- private static void test_splitUint8To2bytes() {
- // 20 = 0x14
- byte[] result = splitUint8To2bytes((char) 20);
- if (result[0] == 1 && result[1] == 4) {
- System.out.println("test_splitUint8To2bytes(): pass");
- } else {
- System.out.println("test_splitUint8To2bytes(): fail");
- }
- }
-
- private static void test_combine2bytesToOne() {
- byte high = 0x01;
- byte low = 0x04;
- if (combine2bytesToOne(high, low) == 20) {
- System.out.println("test_combine2bytesToOne(): pass");
- } else {
- System.out.println("test_combine2bytesToOne(): fail");
- }
- }
-
- private static void test_convertChar2Uint8() {
- byte b1 = 'a';
- // -128: 1000 0000 should be 128 in unsigned char
- // -1: 1111 1111 should be 255 in unsigned char
- byte b2 = (byte) -128;
- byte b3 = (byte) -1;
- if (convertByte2Uint8(b1) == 97 && convertByte2Uint8(b2) == 128
- && convertByte2Uint8(b3) == 255) {
- System.out.println("test_convertChar2Uint8(): pass");
- } else {
- System.out.println("test_convertChar2Uint8(): fail");
- }
- }
-
- private static void test_convertUint8toByte() {
- char c1 = 'a';
- // 128: 1000 0000 should be -128 in byte
- // 255: 1111 1111 should be -1 in byte
- char c2 = 128;
- char c3 = 255;
- if (convertUint8toByte(c1) == 97 && convertUint8toByte(c2) == -128
- && convertUint8toByte(c3) == -1) {
- System.out.println("test_convertUint8toByte(): pass");
- } else {
- System.out.println("test_convertUint8toByte(): fail");
- }
- }
-
- private static void test_parseBssid() {
- byte b[] = {15, -2, 52, -102, -93, -60};
- if(parseBssid(b).equals("0ffe349aa3c4"))
- {
- System.out.println("test_parseBssid(): pass");
- }
- else
- {
- System.out.println("test_parseBssid(): fail");
- }
- }
-
- public static void main(String args[]) {
- test_convertUint8toByte();
- test_convertChar2Uint8();
- test_splitUint8To2bytes();
- test_combine2bytesToOne();
- test_parseBssid();
- }
-
-}
diff --git a/android/app/src/main/java/cc/seeed/iot/esptouch/util/CRC8.java b/android/app/src/main/java/cc/seeed/iot/esptouch/util/CRC8.java
deleted file mode 100644
index 1f893d4..0000000
--- a/android/app/src/main/java/cc/seeed/iot/esptouch/util/CRC8.java
+++ /dev/null
@@ -1,67 +0,0 @@
-package cc.seeed.iot.esptouch.util;
-
-import java.util.zip.Checksum;
-
-public class CRC8 implements Checksum {
-
- private final short init;
-
- private static final short[] crcTable = new short[256];
-
- private short value;
-
- private static final short CRC_POLYNOM = 0x8c;
-
- private static final short CRC_INITIAL = 0x00;
-
- static {
- for (int dividend = 0; dividend < 256; dividend++) {
- int remainder = dividend;// << 8;
- for (int bit = 0; bit < 8; ++bit)
- if ((remainder & 0x01) != 0)
- remainder = (remainder >>> 1) ^ CRC_POLYNOM;
- else
- remainder >>>= 1;
- crcTable[dividend] = (short) remainder;
- }
- }
-
- public CRC8() {
- this.value = this.init = CRC_INITIAL;
- }
-
- @Override
- public void update(byte[] buffer, int offset, int len) {
- for (int i = 0; i < len; i++) {
- int data = buffer[offset + i] ^ value;
- value = (short) (crcTable[data & 0xff] ^ (value << 8));
- }
- }
-
- /**
- * Updates the current checksum with the specified array of bytes.
- * Equivalent to calling update(buffer, 0, buffer.length)
.
- *
- * @param buffer
- * the byte array to update the checksum with
- */
- public void update(byte[] buffer) {
- update(buffer, 0, buffer.length);
- }
-
- @Override
- public void update(int b) {
- update(new byte[] { (byte) b }, 0, 1);
- }
-
- @Override
- public long getValue() {
- return value & 0xff;
- }
-
- @Override
- public void reset() {
- value = init;
- }
-
-}
diff --git a/android/app/src/main/java/cc/seeed/iot/esptouch/util/EspNetUtil.java b/android/app/src/main/java/cc/seeed/iot/esptouch/util/EspNetUtil.java
deleted file mode 100644
index a0b94d1..0000000
--- a/android/app/src/main/java/cc/seeed/iot/esptouch/util/EspNetUtil.java
+++ /dev/null
@@ -1,93 +0,0 @@
-package cc.seeed.iot.esptouch.util;
-
-import android.content.Context;
-import android.net.wifi.WifiInfo;
-import android.net.wifi.WifiManager;
-
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-
-public class EspNetUtil {
-
- /**
- * get the local ip address by Android System
- *
- * @param context
- * the context
- * @return the local ip addr allocated by Ap
- */
- public static InetAddress getLocalInetAddress(Context context) {
- WifiManager wm = (WifiManager) context
- .getSystemService(Context.WIFI_SERVICE);
- WifiInfo wifiInfo = wm.getConnectionInfo();
- int localAddrInt = wifiInfo.getIpAddress();
- String localAddrStr = __formatString(localAddrInt);
- InetAddress localInetAddr = null;
- try {
- localInetAddr = InetAddress.getByName(localAddrStr);
- } catch (UnknownHostException e) {
- e.printStackTrace();
- }
- return localInetAddr;
- }
-
- private static String __formatString(int value) {
- String strValue = "";
- byte[] ary = __intToByteArray(value);
- for (int i = ary.length - 1; i >= 0; i--) {
- strValue += (ary[i] & 0xFF);
- if (i > 0) {
- strValue += ".";
- }
- }
- return strValue;
- }
-
- private static byte[] __intToByteArray(int value) {
- byte[] b = new byte[4];
- for (int i = 0; i < 4; i++) {
- int offset = (b.length - 1 - i) * 8;
- b[i] = (byte) ((value >>> offset) & 0xFF);
- }
- return b;
- }
-
- /**
- * parse InetAddress
- *
- * @param inetAddrBytes
- * @return
- */
- public static InetAddress parseInetAddr(byte[] inetAddrBytes, int offset,
- int count) {
- InetAddress inetAddress = null;
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < count; i++) {
- sb.append(Integer.toString(inetAddrBytes[offset + i] & 0xff));
- if (i != count-1) {
- sb.append('.');
- }
- }
- try {
- inetAddress = InetAddress.getByName(sb.toString());
- } catch (UnknownHostException e) {
- e.printStackTrace();
- }
- return inetAddress;
- }
-
- /**
- * parse bssid
- *
- * @param bssid the bssid
- * @return byte converted from bssid
- */
- public static byte[] parseBssid2bytes(String bssid) {
- String bssidSplits[] = bssid.split(":");
- byte[] result = new byte[bssidSplits.length];
- for(int i = 0;i < bssidSplits.length; i++) {
- result[i] = (byte) Integer.parseInt(bssidSplits[i], 16);
- }
- return result;
- }
-}
diff --git a/android/app/src/main/java/cc/seeed/iot/ui_ap_config/ApConnectActivity.java b/android/app/src/main/java/cc/seeed/iot/ui_ap_config/ApConnectActivity.java
index aedc81c..7ec7ad2 100644
--- a/android/app/src/main/java/cc/seeed/iot/ui_ap_config/ApConnectActivity.java
+++ b/android/app/src/main/java/cc/seeed/iot/ui_ap_config/ApConnectActivity.java
@@ -34,7 +34,7 @@
import cc.seeed.iot.webapi.IotService;
import cc.seeed.iot.webapi.model.Node;
import cc.seeed.iot.webapi.model.NodeListResponse;
-import cc.seeed.iot.webapi.model.NodeResponse;
+import cc.seeed.iot.webapi.model.SuccessResponse;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
@@ -210,12 +210,10 @@ protected Boolean doInBackground(Void... params) {
iot.nodesList(new Callback() {
@Override
public void success(NodeListResponse nodeListResponse, Response response) {
- if (nodeListResponse.status.equals("200")) {
- for (Node n : nodeListResponse.nodes) {
- if (n.node_sn.equals(node_sn) && n.online) {
- state_online = true;
- break;
- }
+ for (Node n : nodeListResponse.nodes) {
+ if (n.node_sn.equals(node_sn) && n.online) {
+ state_online = true;
+ break;
}
}
}
@@ -271,27 +269,19 @@ private void attemptRename(final String node_name) {
User user = ((MyApplication) getApplication()).getUser();
api.setAccessToken(user.user_key);
IotService iot = api.getService();
- iot.nodesRename(node_name, node_sn, new Callback() {
+ iot.nodesRename(node_name, node_sn, new Callback() {
@Override
- public void success(NodeResponse nodeResponse, Response response) {
- String status = nodeResponse.status;
- if (status.equals("200")) {
- mProgressBar.dismiss();
-
- Intent intent = new Intent(ApConnectActivity.this, MainScreenActivity.class);
- intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
- startActivity(intent);
-
- } else {
- mProgressBar.dismiss();
- Toast.makeText(ApConnectActivity.this, "Rename Node fail!", Toast.LENGTH_LONG).show();
- }
+ public void success(SuccessResponse successResponse, Response response) {
+ mProgressBar.dismiss();
+ Intent intent = new Intent(ApConnectActivity.this, MainScreenActivity.class);
+ intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
+ startActivity(intent);
}
@Override
public void failure(RetrofitError error) {
mProgressBar.dismiss();
- Toast.makeText(ApConnectActivity.this, "Connect server error!", Toast.LENGTH_LONG).show();
+ Toast.makeText(ApConnectActivity.this, error.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
});
}
diff --git a/android/app/src/main/java/cc/seeed/iot/ui_ap_config/GoReadyActivity.java b/android/app/src/main/java/cc/seeed/iot/ui_ap_config/GoReadyActivity.java
index 71b0603..b0517de 100644
--- a/android/app/src/main/java/cc/seeed/iot/ui_ap_config/GoReadyActivity.java
+++ b/android/app/src/main/java/cc/seeed/iot/ui_ap_config/GoReadyActivity.java
@@ -78,30 +78,24 @@ private void attemptLogin(final String node_name) {
api.setAccessToken(user.user_key);
IotService iot = api.getService();
iot.nodesCreate(node_name, new Callback() {
- @Override
- public void success(NodeResponse nodeResponse, Response response) {
- String status = nodeResponse.status;
- if (status.equals("200")) {
- mProgressBar.dismiss();
-
- node_key = nodeResponse.node_key;
- node_sn = nodeResponse.node_sn;
- Intent intent = new Intent(GoReadyActivity.this, WifiWioListActivity.class);
- intent.putExtra("node_key", node_key);
- intent.putExtra("node_sn", node_sn);
- startActivity(intent);
- } else {
- mProgressBar.dismiss();
- Toast.makeText(GoReadyActivity.this, "Create Node fail!", Toast.LENGTH_LONG).show();
+ @Override
+ public void success(NodeResponse nodeResponse, Response response) {
+ mProgressBar.dismiss();
+ node_key = nodeResponse.node_key;
+ node_sn = nodeResponse.node_sn;
+ Intent intent = new Intent(GoReadyActivity.this, WifiWioListActivity.class);
+ intent.putExtra("node_key", node_key);
+ intent.putExtra("node_sn", node_sn);
+ startActivity(intent);
+ }
+
+ @Override
+ public void failure(RetrofitError error) {
+ mProgressBar.dismiss();
+ Toast.makeText(GoReadyActivity.this, error.getLocalizedMessage(), Toast.LENGTH_LONG).show();
+ }
}
- }
-
- @Override
- public void failure(RetrofitError error) {
- mProgressBar.dismiss();
- Toast.makeText(GoReadyActivity.this, "Connect server error!", Toast.LENGTH_LONG).show();
- }
- });
+ );
}
}
diff --git a/android/app/src/main/java/cc/seeed/iot/ui_login/LoginActivity.java b/android/app/src/main/java/cc/seeed/iot/ui_login/LoginActivity.java
index a695ec6..a396e67 100644
--- a/android/app/src/main/java/cc/seeed/iot/ui_login/LoginActivity.java
+++ b/android/app/src/main/java/cc/seeed/iot/ui_login/LoginActivity.java
@@ -22,9 +22,10 @@
import cc.seeed.iot.util.Common;
import cc.seeed.iot.webapi.IotApi;
import cc.seeed.iot.webapi.IotService;
-import cc.seeed.iot.webapi.model.UserResponse;
+import cc.seeed.iot.webapi.model.LoginResponse;
import retrofit.Callback;
import retrofit.RetrofitError;
+import retrofit.client.Response;
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "LoginActivity";
@@ -127,12 +128,12 @@ public void login() {
}
- public void onLoginSuccess(String email, UserResponse userResponse) {
+ public void onLoginSuccess(String email, LoginResponse loginResponse) {
_loginButton.setEnabled(true);
user.email = email;
- user.user_key = userResponse.token;
- user.user_id = userResponse.user_id;
+ user.user_key = loginResponse.token;
+ user.user_id = loginResponse.user_id;
((MyApplication) getApplication()).setUser(user);
((MyApplication) getApplication()).setLoginState(true);
Intent intent = new Intent(this, MainScreenActivity.class);
@@ -175,25 +176,19 @@ private void attemptLogin(final ProgressDialog progressDialog) {
IotApi api = new IotApi();
IotService iot = api.getService();
- iot.userLogin(email, password, new Callback() {
+ iot.userLogin(email, password, new Callback() {
@Override
- public void success(UserResponse userResponse, retrofit.client.Response response) {
- String status = userResponse.status;
- if (status.equals("200")) {
- onLoginSuccess(email, userResponse);
- } else {
- onLoginFailed();
- _emailText.setError(userResponse.msg);
- _emailText.requestFocus();
- }
+ public void success(LoginResponse loginResponse, Response response) {
+ onLoginSuccess(email, loginResponse);
progressDialog.dismiss();
}
@Override
public void failure(RetrofitError error) {
+ _emailText.setError(error.getLocalizedMessage());
+ _emailText.requestFocus();
progressDialog.dismiss();
onLoginFailed();
-// Toast.makeText(LoginActivity.this, R.string.ConnectServerFail, Toast.LENGTH_LONG).show();
}
});
}
diff --git a/android/app/src/main/java/cc/seeed/iot/ui_login/ResetActivity.java b/android/app/src/main/java/cc/seeed/iot/ui_login/ResetActivity.java
index 047fdc0..58504af 100644
--- a/android/app/src/main/java/cc/seeed/iot/ui_login/ResetActivity.java
+++ b/android/app/src/main/java/cc/seeed/iot/ui_login/ResetActivity.java
@@ -18,9 +18,10 @@
import cc.seeed.iot.R;
import cc.seeed.iot.webapi.IotApi;
import cc.seeed.iot.webapi.IotService;
-import cc.seeed.iot.webapi.model.CommonResponse;
+import cc.seeed.iot.webapi.model.SuccessResponse;
import retrofit.Callback;
import retrofit.RetrofitError;
+import retrofit.client.Response;
public class ResetActivity extends AppCompatActivity {
private static final String TAG = "ResetActivity";
@@ -105,34 +106,31 @@ public boolean validate() {
private boolean resetPassword(String email, final ProgressDialog progressDialog) {
IotApi api = new IotApi();
IotService iot = api.getService();
- iot.userRetrievePassword(email, new Callback() {
+ iot.userRetrievePassword(email, new Callback() {
@Override
- public void success(CommonResponse response, retrofit.client.Response response1) {
- String status = response.status;
+ public void success(SuccessResponse successResponse, Response response1) {
progressDialog.dismiss();
- if (status.equals("200")) {
- onResetSuccess();
- AlertDialog.Builder builder = new AlertDialog.Builder(ResetActivity.this);
- builder.setPositiveButton(R.string.ok, null).create();
- builder.setTitle("Success");
- builder.setMessage(response.msg);
- builder.show();
- } else {
- progressDialog.dismiss();
- onResetFailed();
- _emailText.setError(response.msg);
- _emailText.requestFocus();
- }
+ onResetSuccess();
+ AlertDialog.Builder builder = new AlertDialog.Builder(ResetActivity.this);
+ builder.setPositiveButton(R.string.ok, null).create();
+ builder.setTitle("Success");
+ builder.setMessage(successResponse.result);
+ builder.show();
}
@Override
public void failure(RetrofitError error) {
+ progressDialog.dismiss();
+ onResetFailed();
+ _emailText.setError(error.getLocalizedMessage());
+ _emailText.requestFocus();
Toast.makeText(ResetActivity.this, R.string.ConnectServerFail, Toast.LENGTH_LONG).show();
}
});
return true;
}
+
private void hideKeyboard() {
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
diff --git a/android/app/src/main/java/cc/seeed/iot/ui_login/SignInDialogFragment.java b/android/app/src/main/java/cc/seeed/iot/ui_login/SignInDialogFragment.java
deleted file mode 100644
index 6558e31..0000000
--- a/android/app/src/main/java/cc/seeed/iot/ui_login/SignInDialogFragment.java
+++ /dev/null
@@ -1,314 +0,0 @@
-package cc.seeed.iot.ui_login;
-
-import android.animation.Animator;
-import android.animation.AnimatorListenerAdapter;
-import android.annotation.TargetApi;
-import android.app.AlertDialog;
-import android.app.Dialog;
-import android.app.DialogFragment;
-import android.app.ProgressDialog;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.os.Build;
-import android.os.Bundle;
-import android.text.TextUtils;
-import android.util.Log;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.widget.AutoCompleteTextView;
-import android.widget.Button;
-import android.widget.EditText;
-import android.widget.TextView;
-import android.widget.Toast;
-
-import cc.seeed.iot.MyApplication;
-import cc.seeed.iot.R;
-import cc.seeed.iot.datastruct.User;
-import cc.seeed.iot.ui_main.MainScreenActivity;
-import cc.seeed.iot.util.Common;
-import cc.seeed.iot.webapi.IotApi;
-import cc.seeed.iot.webapi.IotService;
-import cc.seeed.iot.webapi.model.CommonResponse;
-import cc.seeed.iot.webapi.model.UserResponse;
-import retrofit.Callback;
-import retrofit.RetrofitError;
-
-/**
- * Created by tenwong on 15/7/1.
- */
-public class SignInDialogFragment extends DialogFragment {
- public static final String TAG = "SignInDialogFragment";
- Context context;
- User user;
-
- AlertDialog alertDialog;
- AlertDialog resetPasswordDialog;
-
- private AutoCompleteTextView mEmailView;
- private EditText mPasswordView;
- private TextView mForgotPwdView;
- private TextView mSwitchAreaView;
-
- private View mProgressView;
- private View mLoginFormView;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- context = getActivity();
-
- user = ((MyApplication) getActivity().getApplication()).getUser();
- }
-
- @Override
- public Dialog onCreateDialog(Bundle savedInstanceState) {
- LayoutInflater inflater = getActivity().getLayoutInflater();
- View view = inflater.inflate(R.layout.dialog_sign_in, null);
-
-
- mEmailView = (AutoCompleteTextView) view.findViewById(R.id.email);
- mPasswordView = (EditText) view.findViewById(R.id.password);
- mForgotPwdView = (TextView) view.findViewById(R.id.forgot_password);
- mSwitchAreaView = (TextView) view.findViewById(R.id.switch_area);
- mProgressView = view.findViewById(R.id.login_progress);
- mLoginFormView = view.findViewById(R.id.email_login_form);
-
-// boolean result = Util.checkIsChina(getActivity());
-// if (result) {
- mSwitchAreaView.setVisibility(View.VISIBLE);
-// } else {
-// mSwitchAreaView.setVisibility(View.GONE);
-// }
-
- if (((MyApplication) getActivity().getApplication()).getOtaServerUrl().equals(Common.OTA_CHINA_URL)) {
- mSwitchAreaView.setText(R.string.setup_switch_international);
- ((MyApplication) getActivity().getApplication()).setExchangeServerUrl(Common.EXCHANGE_CHINA_URL);
- } else if (((MyApplication) getActivity().getApplication()).getOtaServerUrl().equals(Common.OTA_INTERNATIONAL_URL)) {
- mSwitchAreaView.setText(R.string.setup_switch_china);
- ((MyApplication) getActivity().getApplication()).setExchangeServerUrl(Common.EXCHANGE_INTERNATIONAL_URL);
- } else
- mSwitchAreaView.setText(((MyApplication) getActivity().getApplication()).getOtaServerUrl());
-
-
-
- AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
- builder.setView(view);
- builder.setTitle(R.string.setup_signin);
- builder.setPositiveButton(R.string.setup_signin, null);
- builder.setNegativeButton(R.string.cancel, null);
-
- return builder.create();
- }
-
-
- @Override
- public void onStart() {
- super.onStart(); //super.onStart() is where dialog.show() is actually called on the underlying dialog, so we have to do it after this point
- alertDialog = (AlertDialog) getDialog();
- if (alertDialog != null) {
- Button positiveButton;
- positiveButton = (Button) alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
- positiveButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- attemptLogin();
- }
- });
- }
-
-
- mSwitchAreaView.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- if (mSwitchAreaView.getText().toString().equals(getString(R.string.setup_switch_international))) {
- mSwitchAreaView.setText(R.string.setup_switch_china);
- ((MyApplication) getActivity().getApplication()).setOtaServerUrl(Common.OTA_INTERNATIONAL_URL);
- ((MyApplication) getActivity().getApplication()).setExchangeServerUrl(Common.EXCHANGE_INTERNATIONAL_URL);
- } else {
- mSwitchAreaView.setText(R.string.setup_switch_international);
- ((MyApplication) getActivity().getApplication()).setOtaServerUrl(Common.OTA_CHINA_URL);
- ((MyApplication) getActivity().getApplication()).setExchangeServerUrl(Common.EXCHANGE_CHINA_URL);
- }
- }
- });
-
- mForgotPwdView.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- alertDialog.dismiss();
-
- LayoutInflater inflater = getActivity().getLayoutInflater();
- View forgetPwdView = inflater.inflate(R.layout.dialog_email_input, null);
- final AutoCompleteTextView emailView =
- (AutoCompleteTextView) forgetPwdView.findViewById(R.id.email);
- AlertDialog.Builder builder = new AlertDialog.Builder(context);
- builder.setTitle("Reset Password");
- builder.setView(forgetPwdView);
- builder.setPositiveButton(R.string.ok, null);
- builder.setNegativeButton(R.string.cancel, null);
- builder.setCancelable(false);
- resetPasswordDialog = builder.create();
- resetPasswordDialog.show();
-
- Button positiveButton = resetPasswordDialog.getButton(DialogInterface.BUTTON_POSITIVE);
- positiveButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- Log.e(TAG, "sd");
- String email = emailView.getText().toString();
- if (!isEmailValid(email)) {
- emailView.setError("Invalid email");
- return;
- }
- resetPassword(email, emailView);
- }
- });
- }
- });
- }
-
- private void attemptLogin() {
- mEmailView.setError(null);
- mPasswordView.setError(null);
-
- String email = mEmailView.getText().toString();
- String password = mPasswordView.getText().toString();
-
- boolean cancel = false;
- View focusView = null;
-
- if (TextUtils.isEmpty(password) || !isPasswordValid(password)) {
- mPasswordView.setError("invalid Password");
- focusView = mPasswordView;
- cancel = true;
- }
-
- if (TextUtils.isEmpty(email)) {
- mEmailView.setError("Require email");
- focusView = mEmailView;
- cancel = true;
-
- } else if (!isEmailValid(email)) {
- mEmailView.setError("Invalid email");
- focusView = mEmailView;
- cancel = true;
- }
-
- if (cancel) {
- focusView.requestFocus();
- } else {
- showProgress(true);
- final String fianlEmail = email;
- IotApi api = new IotApi();
- IotService iot = api.getService();
- iot.userLogin(email, password, new Callback() {
- @Override
- public void success(UserResponse userResponse, retrofit.client.Response response) {
- String status = userResponse.status;
- if (status.equals("200")) {
- alertDialog.dismiss();
- user.email = fianlEmail;
- user.user_key = userResponse.token;
- user.user_id = userResponse.user_id;
- ((MyApplication) getActivity().getApplication()).setUser(user);
- ((MyApplication) getActivity().getApplication()).setLoginState(true);
- Intent intent = new Intent(context, MainScreenActivity.class);
- context.startActivity(intent);
- } else {
- showProgress(false);
- mEmailView.setError(userResponse.msg);
- mEmailView.requestFocus();
- }
- }
-
- @Override
- public void failure(RetrofitError error) {
- Toast.makeText(context, "connect server fail...", Toast.LENGTH_LONG).show();
- }
- });
- }
- }
-
- private boolean resetPassword(String email, final AutoCompleteTextView emailView) {
- final ProgressDialog progressDialog = new ProgressDialog(context);
- progressDialog.setMessage("Resetting your password...");
- progressDialog.setCancelable(false);
- progressDialog.show();
- IotApi api = new IotApi();
- IotService iot = api.getService();
- iot.userRetrievePassword(email, new Callback() {
- @Override
- public void success(CommonResponse response, retrofit.client.Response response1) {
- String status = response.status;
- if (status.equals("200")) {
- resetPasswordDialog.dismiss();
- progressDialog.dismiss();
- AlertDialog.Builder builder = new AlertDialog.Builder(context);
- builder.setPositiveButton(R.string.ok, null).create();
- builder.setTitle("Success");
- builder.setMessage(response.msg);
- builder.show();
- } else {
- progressDialog.dismiss();
- emailView.setError(response.msg);
- emailView.requestFocus();
- }
- }
-
- @Override
- public void failure(RetrofitError error) {
- Toast.makeText(context, "connect server fail...", Toast.LENGTH_LONG).show();
- }
- });
-
- return true;
- }
-
- /**
- * Shows the progress UI and hides the login form.
- */
- @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
- public void showProgress(final boolean show) {
- // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
- // for very easy animations. If available, use these APIs to fade-in
- // the progress spinner.
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
- int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
-
- mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
- mLoginFormView.animate().setDuration(shortAnimTime).alpha(
- show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
- @Override
- public void onAnimationEnd(Animator animation) {
- mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
- }
- });
-
- mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
- mProgressView.animate().setDuration(shortAnimTime).alpha(
- show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
- @Override
- public void onAnimationEnd(Animator animation) {
- mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
- }
- });
- } else {
- // The ViewPropertyAnimator APIs are not available, so simply show
- // and hide the relevant UI components.
- mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
- mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
- }
- }
-
- private boolean isEmailValid(String email) {
- return email.contains("@");
- }
-
- private boolean isPasswordValid(String password) {
- return password.length() >= 6;
- }
-
-}
-
-
diff --git a/android/app/src/main/java/cc/seeed/iot/ui_login/SignUpDialogFragment.java b/android/app/src/main/java/cc/seeed/iot/ui_login/SignUpDialogFragment.java
deleted file mode 100644
index 9ec9a5e..0000000
--- a/android/app/src/main/java/cc/seeed/iot/ui_login/SignUpDialogFragment.java
+++ /dev/null
@@ -1,233 +0,0 @@
-package cc.seeed.iot.ui_login;
-
-import android.animation.Animator;
-import android.animation.AnimatorListenerAdapter;
-import android.annotation.TargetApi;
-import android.app.AlertDialog;
-import android.app.Dialog;
-import android.app.DialogFragment;
-import android.content.Context;
-import android.content.Intent;
-import android.os.Build;
-import android.os.Bundle;
-import android.text.TextUtils;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.widget.AutoCompleteTextView;
-import android.widget.Button;
-import android.widget.EditText;
-import android.widget.TextView;
-import android.widget.Toast;
-
-import cc.seeed.iot.MyApplication;
-import cc.seeed.iot.R;
-import cc.seeed.iot.datastruct.User;
-import cc.seeed.iot.ui_main.MainScreenActivity;
-import cc.seeed.iot.util.Common;
-import cc.seeed.iot.webapi.IotApi;
-import cc.seeed.iot.webapi.IotService;
-import cc.seeed.iot.webapi.model.UserResponse;
-import retrofit.Callback;
-import retrofit.RetrofitError;
-
-/**
- * Created by tenwong on 15/6/30.
- */
-public class SignUpDialogFragment extends DialogFragment {
- Context context;
- User user;
-
- AutoCompleteTextView mEmailView;
- EditText mPasswordView;
- EditText mPasswordVerifyView;
- private View mProgressView;
- private View mLoginRegisterView;
- private AlertDialog alertDialog;
- private TextView mSwitchAreaView;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- context = getActivity();
- user = ((MyApplication) getActivity().getApplication()).getUser();
- }
-
- @Override
- public Dialog onCreateDialog(Bundle savedInstanceState) {
- AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
- LayoutInflater inflater = getActivity().getLayoutInflater();
- View view = inflater.inflate(R.layout.dialog_sign_up, null);
-
- mEmailView = (AutoCompleteTextView) view.findViewById(R.id.email);
- mPasswordView = (EditText) view.findViewById(R.id.password);
- mPasswordVerifyView = (EditText) view.findViewById(R.id.verify);
- mProgressView = view.findViewById(R.id.login_progress);
- mLoginRegisterView = view.findViewById(R.id.email_register_form);
- mSwitchAreaView = (TextView) view.findViewById(R.id.switch_area);
-
-// boolean result = Util.checkIsChina(getActivity());
-// if (result) {
- mSwitchAreaView.setVisibility(View.VISIBLE);
-// } else {
-// mSwitchAreaView.setVisibility(View.GONE);
-// }
-
- if (((MyApplication) getActivity().getApplication()).getOtaServerUrl().equals(Common.OTA_CHINA_URL))
- mSwitchAreaView.setText(R.string.setup_switch_international);
- else if (((MyApplication) getActivity().getApplication()).getOtaServerUrl().equals(Common.OTA_INTERNATIONAL_URL))
- mSwitchAreaView.setText(R.string.setup_switch_china);
- else
- mSwitchAreaView.setText(((MyApplication) getActivity().getApplication()).getOtaServerUrl());
-
- builder.setView(view);
- builder.setTitle("Sign Up");
- builder.setPositiveButton("Sign up", null);
- builder.setNegativeButton(R.string.cancel, null);
-
- return builder.create();
- }
-
- @Override
- public void onStart() {
- super.onStart();
- alertDialog = (AlertDialog) getDialog();
- if (alertDialog != null) {
- Button positiveButton = (Button) alertDialog.getButton(Dialog.BUTTON_POSITIVE);
- positiveButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- attemptRegister();
- }
- });
- }
-
- mSwitchAreaView.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- if (mSwitchAreaView.getText().toString().equals(getString(R.string.setup_switch_international))) {
- mSwitchAreaView.setText(R.string.setup_switch_china);
- ((MyApplication) getActivity().getApplication()).setOtaServerUrl(Common.OTA_INTERNATIONAL_URL);
- } else {
- mSwitchAreaView.setText(R.string.setup_switch_international);
- ((MyApplication) getActivity().getApplication()).setOtaServerUrl(Common.OTA_CHINA_URL);
- }
- }
- });
- }
-
-
- private void attemptRegister() {
- mEmailView.setError(null);
- mPasswordView.setError(null);
-
- String email = mEmailView.getText().toString();
- String password = mPasswordView.getText().toString();
- String passwordVerify = mPasswordVerifyView.getText().toString();
-
- boolean cancel = false;
- View focusView = null;
-
- if (!(password.equals(passwordVerify))) {
- mPasswordVerifyView.setError("not same password");
- focusView = mPasswordVerifyView;
- cancel = true;
- }
-
- if (TextUtils.isEmpty(password) || !isPasswordValid(password)) {
- mPasswordView.setError("invalid Password");
- focusView = mPasswordView;
- cancel = true;
- }
-
-
- if (TextUtils.isEmpty(email)) {
- mEmailView.setError("Require email");
- focusView = mEmailView;
- cancel = true;
-
- } else if (!isEmailValid(email)) {
- mEmailView.setError("Invalid email");
- focusView = mEmailView;
- cancel = true;
- }
-
- if (cancel) {
- focusView.requestFocus();
- } else {
- showProgress(true);
- final String fianlEmail = email;
- IotApi api = new IotApi();
- IotService iot = api.getService();
- iot.userCreate(email, password, new Callback() {
- @Override
- public void success(UserResponse userResponse, retrofit.client.Response response) {
- String status = userResponse.status;
- if (status.equals("200")) {
- alertDialog.dismiss();
- user.email = fianlEmail;
- user.user_key = userResponse.token;
- user.user_id = userResponse.user_id;
- ((MyApplication) getActivity().getApplication()).setUser(user);
- ((MyApplication) getActivity().getApplication()).setLoginState(true);
- Intent intent = new Intent(context, MainScreenActivity.class);
- context.startActivity(intent);
- } else {
- showProgress(false);
- mEmailView.setError(userResponse.msg);
- mEmailView.requestFocus();
- }
- }
-
- @Override
- public void failure(RetrofitError error) {
- Toast.makeText(context, "Connect sever fail...", Toast.LENGTH_LONG).show();
- }
- });
- }
- }
-
- private boolean isEmailValid(String email) {
- return email.contains("@");
- }
-
- private boolean isPasswordValid(String password) {
- return password.length() >= 6;
- }
-
-
- /**
- * Shows the progress UI and hides the login form.
- */
- @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
- public void showProgress(final boolean show) {
- // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
- // for very easy animations. If available, use these APIs to fade-in
- // the progress spinner.
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
- int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
-
- mLoginRegisterView.setVisibility(show ? View.GONE : View.VISIBLE);
- mLoginRegisterView.animate().setDuration(shortAnimTime).alpha(
- show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
- @Override
- public void onAnimationEnd(Animator animation) {
- mLoginRegisterView.setVisibility(show ? View.GONE : View.VISIBLE);
- }
- });
-
- mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
- mProgressView.animate().setDuration(shortAnimTime).alpha(
- show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
- @Override
- public void onAnimationEnd(Animator animation) {
- mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
- }
- });
- } else {
- // The ViewPropertyAnimator APIs are not available, so simply show
- // and hide the relevant UI components.
- mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
- mLoginRegisterView.setVisibility(show ? View.GONE : View.VISIBLE);
- }
- }
-}
diff --git a/android/app/src/main/java/cc/seeed/iot/ui_login/SignupActivity.java b/android/app/src/main/java/cc/seeed/iot/ui_login/SignupActivity.java
index ea45118..0c238be 100644
--- a/android/app/src/main/java/cc/seeed/iot/ui_login/SignupActivity.java
+++ b/android/app/src/main/java/cc/seeed/iot/ui_login/SignupActivity.java
@@ -116,7 +116,7 @@ public void onSignupSuccess(String email, UserResponse userResponse) {
_signupButton.setEnabled(true);
user.email = email;
user.user_key = userResponse.token;
- user.user_id = userResponse.user_id;
+// user.user_id = userResponse.user_id;
((MyApplication) getApplication()).setUser(user);
((MyApplication) getApplication()).setLoginState(true);
Intent intent = new Intent(this, MainScreenActivity.class);
@@ -174,23 +174,16 @@ private void attemptRegister(final ProgressDialog progressDialog) {
iot.userCreate(email, password, new Callback() {
@Override
public void success(UserResponse userResponse, retrofit.client.Response response) {
- String status = userResponse.status;
- if (status.equals("200")) {
- onSignupSuccess(email, userResponse);
- } else {
- _emailText.setError(userResponse.msg);
- _emailText.requestFocus();
- onSignupFailed();
- }
+ onSignupSuccess(email, userResponse);
progressDialog.dismiss();
}
@Override
public void failure(RetrofitError error) {
-// Toast.makeText(SignupActivity.this, R.string.ConnectServerFail, Toast.LENGTH_LONG).show();
- progressDialog.dismiss();
+ _emailText.setError(error.getLocalizedMessage());
+ _emailText.requestFocus();
onSignupFailed();
-
+ progressDialog.dismiss();
}
});
}
diff --git a/android/app/src/main/java/cc/seeed/iot/ui_main/ChangePwdActivity.java b/android/app/src/main/java/cc/seeed/iot/ui_main/ChangePwdActivity.java
index fb64040..6a68b23 100644
--- a/android/app/src/main/java/cc/seeed/iot/ui_main/ChangePwdActivity.java
+++ b/android/app/src/main/java/cc/seeed/iot/ui_main/ChangePwdActivity.java
@@ -20,9 +20,11 @@
import cc.seeed.iot.datastruct.User;
import cc.seeed.iot.webapi.IotApi;
import cc.seeed.iot.webapi.IotService;
+import cc.seeed.iot.webapi.model.LoginResponse;
import cc.seeed.iot.webapi.model.UserResponse;
import retrofit.Callback;
import retrofit.RetrofitError;
+import retrofit.client.Response;
public class ChangePwdActivity extends AppCompatActivity {
private static final String TAG = "ChangePwdActivity";
@@ -104,22 +106,17 @@ private void checkOldPassword(final ProgressDialog progressDialog) {
IotApi api = new IotApi();
IotService iot = api.getService();
- iot.userLogin(email, password, new Callback() {
+ iot.userLogin(email, password, new Callback() {
@Override
- public void success(UserResponse userResponse, retrofit.client.Response response) {
- String status = userResponse.status;
- if (status.equals("200")) {
- changePwd(progressDialog);
- } else {
- _oldPwdText.setError("Old password isn't valid");
- _oldPwdText.requestFocus();
- onChanePwdFailed();
- }
+ public void success(LoginResponse loginResponse, Response response) {
+ changePwd(progressDialog);
progressDialog.dismiss();
}
@Override
public void failure(RetrofitError error) {
+ _oldPwdText.setError("Old password isn't valid");
+ _oldPwdText.requestFocus();
progressDialog.dismiss();
onChanePwdFailed();
@@ -133,22 +130,18 @@ private void changePwd(final ProgressDialog progressDialog) {
String access_token = user.user_key;
IotApi api = new IotApi();
IotService iot = api.getService();
- iot.userChangePassword(password, access_token, new Callback() {
+ api.setAccessToken(access_token);
+ iot.userChangePassword(password, new Callback() {
@Override
public void success(UserResponse userResponse, retrofit.client.Response response) {
- String status = userResponse.status;
- if (status.equals("200")) {
- onSavePwdSuccess(userResponse);
- } else {
- _newPwdText.setError(userResponse.msg);
- _newPwdText.requestFocus();
- onChanePwdFailed();
- }
+ onSavePwdSuccess(userResponse);
progressDialog.dismiss();
}
@Override
public void failure(RetrofitError error) {
+ _newPwdText.setError(error.getLocalizedMessage());
+ _newPwdText.requestFocus();
progressDialog.dismiss();
onChanePwdFailed();
}
@@ -158,7 +151,7 @@ public void failure(RetrofitError error) {
public void onSavePwdSuccess(UserResponse userResponse) {
_savePwdButton.setEnabled(true);
user.user_key = userResponse.token;
- user.user_id = userResponse.user_id;
+// user.user_id = userResponse.user_id;
((MyApplication) getApplication()).setUser(user);
Toast.makeText(getBaseContext(), "Password changed successfully.", Toast.LENGTH_LONG).show();
_oldPwdText.setText("");
diff --git a/android/app/src/main/java/cc/seeed/iot/ui_main/MainScreenActivity.java b/android/app/src/main/java/cc/seeed/iot/ui_main/MainScreenActivity.java
index daceddd..33d4f5c 100644
--- a/android/app/src/main/java/cc/seeed/iot/ui_main/MainScreenActivity.java
+++ b/android/app/src/main/java/cc/seeed/iot/ui_main/MainScreenActivity.java
@@ -19,7 +19,6 @@
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
-import android.media.Image;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
@@ -34,17 +33,16 @@
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
-import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
-import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
+import java.util.Map;
import cc.seeed.iot.MyApplication;
import cc.seeed.iot.R;
@@ -59,11 +57,13 @@
import cc.seeed.iot.util.DBHelper;
import cc.seeed.iot.webapi.IotApi;
import cc.seeed.iot.webapi.IotService;
-import cc.seeed.iot.webapi.model.CommonResponse;
+import cc.seeed.iot.webapi.model.GroveDriverListResponse;
import cc.seeed.iot.webapi.model.GroverDriver;
import cc.seeed.iot.webapi.model.Node;
+import cc.seeed.iot.webapi.model.NodeConfigResponse;
+import cc.seeed.iot.webapi.model.NodeJson;
import cc.seeed.iot.webapi.model.NodeListResponse;
-import cc.seeed.iot.webapi.model.NodeResponse;
+import cc.seeed.iot.webapi.model.SuccessResponse;
import cc.seeed.iot.yaml.IotYaml;
import retrofit.Callback;
import retrofit.RetrofitError;
@@ -136,8 +136,8 @@ private void initView() {
} else if (((MyApplication) getApplication()).getOtaServerUrl().equals(Common.OTA_INTERNATIONAL_URL)) {
mEmail.setText(user.email + " (International)");
} else
- mEmail.setText(user.email + " (Customer)\n" +
- ((MyApplication) getApplication()).getOtaServerIP());
+ mEmail.setText(user.email + " (Customer)\n" +
+ ((MyApplication) getApplication()).getOtaServerIP());
}
@@ -217,7 +217,7 @@ public void handleMessage(Message msg) {
mProgressDialog.dismiss();
if (msg.arg2 == 1) {
mAdapter.updateAll(nodes);
- if(nodes.isEmpty()) {
+ if (nodes.isEmpty()) {
mAddTip.setVisibility(View.VISIBLE);
} else {
mAddTip.setVisibility(View.GONE);
@@ -404,9 +404,9 @@ public void onClick(DialogInterface dialog, int which) {
User user = ((MyApplication) MainScreenActivity.this.getApplication()).getUser();
api.setAccessToken(user.user_key);
final IotService iot = api.getService();
- iot.nodesDelete(node.node_sn, new Callback() {
+ iot.nodesDelete(node.node_sn, new Callback() {
@Override
- public void success(NodeResponse nodeResponse, Response response) {
+ public void success(SuccessResponse successResponse, Response response) {
progressDialog.dismiss();
nodes.remove(node);
DBHelper.delNode(node.node_sn);
@@ -447,52 +447,43 @@ private void getNodeList() {
iot.nodesList(new Callback() {
@Override
public void success(NodeListResponse nodeListResponse, Response response) {
- if (nodeListResponse.status.equals("200")) {
- List get_nodes = nodeListResponse.nodes;
- ArrayList delNodes = new ArrayList();
- for (Node n : get_nodes) {
- if (n.name.equals("node000")) {
- iot.nodesDelete(n.node_sn, new Callback() {
- @Override
- public void success(NodeResponse nodeResponse, Response response) {
-
- }
-
- @Override
- public void failure(RetrofitError error) {
-
- }
- });
- delNodes.add(n);
- }
+ List get_nodes = nodeListResponse.nodes;
+ ArrayList delNodes = new ArrayList();
+ for (Node n : get_nodes) {
+ if (n.name.equals("node000")) {
+ iot.nodesDelete(n.node_sn, new Callback() {
+ @Override
+ public void success(SuccessResponse successResponse, Response response) {
+
+ }
+
+ @Override
+ public void failure(RetrofitError error) {
+
+ }
+ });
+ delNodes.add(n);
}
- get_nodes.removeAll(delNodes);
- nodes = get_nodes;
-
- DBHelper.saveNodes(nodes);
-
- Message message = Message.obtain();
- message.arg2 = 1;
- message.what = MESSAGE_NODE_LIST_COMPLETE;
- mHandler.sendMessage(message);
-
- } else {
- Toast.makeText(MainScreenActivity.this, nodeListResponse.msg, Toast.LENGTH_LONG).show();
- Message message = Message.obtain();
- message.arg2 = 0;
- message.what = MESSAGE_NODE_LIST_COMPLETE;
- mHandler.sendMessage(message);
}
+ get_nodes.removeAll(delNodes);
+ nodes = get_nodes;
+
+ DBHelper.saveNodes(nodes);
+
+ Message message = Message.obtain();
+ message.arg2 = 1;
+ message.what = MESSAGE_NODE_LIST_COMPLETE;
+ mHandler.sendMessage(message);
}
@Override
public void failure(RetrofitError error) {
+ Toast.makeText(MainScreenActivity.this, error.getLocalizedMessage(),
+ Toast.LENGTH_LONG).show();
Message message = Message.obtain();
message.arg2 = 0;
message.what = MESSAGE_NODE_LIST_COMPLETE;
mHandler.sendMessage(message);
-
- Toast.makeText(MainScreenActivity.this, "Connect server fail!", Toast.LENGTH_LONG).show();
}
});
@@ -502,14 +493,14 @@ private void getNodesConfig(final Node node, final int position) {
IotApi api = new IotApi();
api.setAccessToken(node.node_key);
final IotService iot = api.getService();
- iot.nodeConfig(new Callback() {
+ iot.nodeConfig(new Callback() {
@Override
- public void success(CommonResponse response, Response response2) {
- if (response.status.equals("200")) {
- String yaml = response.msg;
- saveToDB(yaml);
- } else {
- Log.i(TAG, response.msg);
+ public void success(NodeConfigResponse nodeConfigResponse, Response response) {
+ if (nodeConfigResponse.type.equals("yaml")) {
+ Log.e(TAG, "do not support!");
+ } else if (nodeConfigResponse.type.equals("json")) {
+ NodeJson nodeJson = nodeConfigResponse.config;
+ saveToDB(nodeJson);
}
Message message = Message.obtain();
@@ -520,12 +511,52 @@ public void success(CommonResponse response, Response response2) {
@Override
public void failure(RetrofitError error) {
- Log.e(getClass().getName(), error.toString());
-
+ Log.e(TAG, error.getLocalizedMessage());
}
- private void saveToDB(String yaml) {
- List pinConfigs = IotYaml.getNodeConfig(yaml);
+// private void saveToDB(String yaml) {
+// List pinConfigs = IotYaml.getNodeConfig(yaml);
+// PinConfigDBHelper.delPinConfig(node.node_sn);
+// for (PinConfig pinConfig : pinConfigs) {
+// pinConfig.node_sn = node.node_sn;
+// pinConfig.save();
+// }
+// }
+
+ private void saveToDB(NodeJson nodeJson) {
+ List pinConfigs = new ArrayList<>();
+ List