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> connections = nodeJson.connections; + try { + for (Map l : connections) { + PinConfig pinConfig = new PinConfig(); + pinConfig.sku = l.get("sku"); + pinConfig.selected = true; + switch (l.get("port")) { + case "D0": + pinConfig.position = 1; + break; + case "D1": + pinConfig.position = 2; + break; + case "D2": + pinConfig.position = 3; + break; + case "A0": + pinConfig.position = 4; + break; + case "UART0": + pinConfig.position = 5; + break; + case "I2C0": + pinConfig.position = 6; + break; + } + pinConfigs.add(pinConfig); + } + } catch (Exception e) { + Log.e(TAG, "getNodeConfig:" + e); + } + PinConfigDBHelper.delPinConfig(node.node_sn); for (PinConfig pinConfig : pinConfigs) { pinConfig.node_sn = node.node_sn; @@ -540,10 +571,10 @@ private void getGrovesData() { String token = user.user_key; api.setAccessToken(token); IotService iot = api.getService(); - iot.scanDrivers(new Callback>() { + iot.scanDrivers(new Callback() { @Override - public void success(List groverDrivers, retrofit.client.Response response) { - for (GroverDriver groveDriver : groverDrivers) { + public void success(GroveDriverListResponse groveDriverListResponse, Response response) { + for (GroverDriver groveDriver : groveDriverListResponse.drivers) { groveDriver.save(); } @@ -554,7 +585,7 @@ public void success(List groverDrivers, retrofit.client.Response r @Override public void failure(RetrofitError error) { - Log.e(TAG, error.toString()); + Log.e(TAG, error.getLocalizedMessage()); Message message = Message.obtain(); message.what = MESSAGE_GROVE_LIST_COMPLETE; mHandler.sendMessage(message); diff --git a/android/app/src/main/java/cc/seeed/iot/ui_main/NodePreferenceFragment.java b/android/app/src/main/java/cc/seeed/iot/ui_main/NodePreferenceFragment.java index 2d55f81..32d8105 100644 --- a/android/app/src/main/java/cc/seeed/iot/ui_main/NodePreferenceFragment.java +++ b/android/app/src/main/java/cc/seeed/iot/ui_main/NodePreferenceFragment.java @@ -17,9 +17,8 @@ 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.Node; -import cc.seeed.iot.webapi.model.NodeResponse; +import cc.seeed.iot.webapi.model.SuccessResponse; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; @@ -117,15 +116,10 @@ private void nodeXserverIp(final Node node, String newValue, final EditTextPrefe IotApi api = new IotApi(); api.setAccessToken(node.node_key); final IotService iot = api.getService(); - iot.nodeSettingDataxserver(newValue, new Callback() { + iot.nodeSettingDataxserver(newValue, new Callback() { @Override - public void success(CommonResponse commonResponse, Response response) { + public void success(SuccessResponse successResponse, Response response) { ep_ip.setEnabled(true); - if (!commonResponse.status.equals("200")) { - ep_ip.setSummary(node.dataxserver); - ep_ip.setText(node.dataxserver); - notifyFail(commonResponse.msg); - } } @Override @@ -144,14 +138,10 @@ private void nodeXserverIp(final Node node, String newValue, final SwitchPrefere IotApi api = new IotApi(); api.setAccessToken(node.node_key); final IotService iot = api.getService(); - iot.nodeSettingDataxserver(newValue, new Callback() { + iot.nodeSettingDataxserver(newValue, new Callback() { @Override - public void success(CommonResponse commonResponse, Response response) { + public void success(SuccessResponse successResponse, Response response) { sp_server.setEnabled(true); - if (!commonResponse.status.equals("200")) { - sp_server.setChecked(true); - notifyFail(commonResponse.msg); - } } @Override @@ -170,20 +160,22 @@ private void nodeRename(final Node node, String newName, final EditTextPreferenc User user = ((MyApplication) getActivity().getApplication()).getUser(); api.setAccessToken(user.user_key); final IotService iot = api.getService(); - iot.nodesRename(newName, node.node_sn, new Callback() { + iot.nodesRename(newName, node.node_sn, new Callback() { @Override - public void success(NodeResponse nodeResponse, Response response) { + public void success(SuccessResponse successResponse, Response response) { ep_name.setEnabled(true); - if (!nodeResponse.status.equals("200")) { - ep_ip.setSummary(node.dataxserver); - ep_ip.setText(node.dataxserver); - notifyFail(nodeResponse.msg); - } +// if (!nodeResponse.status.equals("200")) { +// ep_ip.setSummary(node.dataxserver); +// ep_ip.setText(node.dataxserver); +// notifyFail(nodeResponse.msg); +// } } @Override public void failure(RetrofitError error) { Log.e(TAG, "Rename wio link failure!"); + ep_ip.setSummary(node.dataxserver); + ep_ip.setText(node.dataxserver); ep_name.setEnabled(true); ep_name.setSummary(node.name); ep_name.setText(node.name); diff --git a/android/app/src/main/java/cc/seeed/iot/ui_setnode/SetupIotNodeActivity.java b/android/app/src/main/java/cc/seeed/iot/ui_setnode/SetupIotNodeActivity.java index 5da4c3c..00ca6af 100644 --- a/android/app/src/main/java/cc/seeed/iot/ui_setnode/SetupIotNodeActivity.java +++ b/android/app/src/main/java/cc/seeed/iot/ui_setnode/SetupIotNodeActivity.java @@ -16,7 +16,6 @@ import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; -import android.util.Base64; import android.util.Log; import android.util.SparseBooleanArray; import android.util.SparseIntArray; @@ -27,6 +26,7 @@ import android.widget.ImageView; import android.widget.TextView; +import com.google.gson.Gson; import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper; import java.util.ArrayList; @@ -44,8 +44,10 @@ import cc.seeed.iot.util.DBHelper; import cc.seeed.iot.webapi.IotApi; import cc.seeed.iot.webapi.IotService; +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.NodeJson; import cc.seeed.iot.webapi.model.OtaStatusResponse; import retrofit.Callback; import retrofit.RetrofitError; @@ -283,21 +285,12 @@ public boolean onOptionsItemSelected(MenuItem item) { intent.putExtra("node_sn", node.node_sn); startActivity(intent); } else if (id == R.id.update) { - //TODO update firmware if (node.name == null) return true; -// String yaml = "" + -// "GroveMultiChannelGas:\r\n" + -// " sku: 101020088\r\n" + -// " name: Grove-Multichannel Gas Sensor\r\n" + -// " construct_arg_list:\r\n" + -// " pinsda: 4\r\n" + -// " pinscl: 5\r\n"; - - String yaml = NodeConfigHelper.getConfigYaml(pinConfigs); -// Log.i(TAG, pinConfigs.toString()); - Log.i(TAG, "yaml:\n" + yaml); - if (yaml.isEmpty()) { + + NodeJson node_josn = NodeConfigHelper.getConfigJson(pinConfigs); + Log.i(TAG, "node_json:\n" + new Gson().toJson(node_josn)); + if (node_josn.connections.isEmpty()) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Forger add grove?"); builder.setTitle("Tip"); @@ -310,13 +303,9 @@ public void onClick(DialogInterface dialog, int which) { builder.create().show(); return true; } - String Base64Yaml = Base64.encodeToString(yaml.getBytes(), Base64.DEFAULT); - updateNode(node.node_key, Base64Yaml); - - + updateNode(node.node_key, node_josn); return true; } - return super.onOptionsItemSelected(item); } @@ -352,84 +341,70 @@ public boolean onContextItemSelected(MenuItem item) { return super.onContextItemSelected(item); } - private void updateNode(final String node_key, String base64Yaml) { + private void updateNode(final String node_key, NodeJson node_json) { mProgressDialog.show(); mProgressDialog.setMessage("Ready to ota..."); mProgressDialog.getButton(ProgressDialog.BUTTON_POSITIVE).setVisibility(View.INVISIBLE); IotApi api = new IotApi(); + api.setAccessToken(node_key); final IotService iot = api.getService(); - iot.userDownload(node_key, base64Yaml, new Callback() { + iot.userDownload(node_json, new Callback() { @Override public void success(OtaStatusResponse otaStatusResponse, Response response) { - try { - if (otaStatusResponse.status.equals("200")) { - mProgressDialog.setMessage(otaStatusResponse.ota_msg); - displayStatus(node_key); - } else { - mProgressDialog.setMessage("Error:" + otaStatusResponse.msg); - mProgressDialog.getButton(ProgressDialog.BUTTON_POSITIVE).setVisibility(View.VISIBLE); - } - } catch (Exception e) { - mProgressDialog.dismiss(); - Log.e(TAG, "userDownload:" + e); - } - + mProgressDialog.setMessage(otaStatusResponse.ota_msg); + displayStatus(node_key); } @Override public void failure(RetrofitError error) { - mProgressDialog.dismiss(); - Log.e(TAG, "error:" + error); + mProgressDialog.setMessage("Error:" + error.getLocalizedMessage()); + mProgressDialog.getButton(ProgressDialog.BUTTON_POSITIVE).setVisibility(View.VISIBLE); } }); } private void displayStatus(final String node_key) { IotApi api = new IotApi(); + api.setAccessToken(node_key); final IotService iot = api.getService(); - iot.otaStatus(node_key, new Callback() { - @Override - public void success(OtaStatusResponse otaStatusResponse, Response response) { - if (otaStatusResponse.status.equals("200")) { - if (otaStatusResponse.ota_status.equals("going")) { - displayStatus(node_key); - mProgressDialog.setMessage(otaStatusResponse.ota_msg); - } else if (otaStatusResponse.ota_status.equals("done")) { - mProgressDialog.dismiss(); - - Message message = Message.obtain(); - message.what = MESSAGE_UPDATE_DONE; - message.obj = otaStatusResponse.ota_msg; - mHandler.sendMessage(message); - - } else if (otaStatusResponse.ota_status.equals("error")) { - mProgressDialog.setMessage(otaStatusResponse.ota_status + ":" + otaStatusResponse.ota_msg); - mProgressDialog.getButton(ProgressDialog.BUTTON_POSITIVE).setVisibility(View.VISIBLE); - mProgressDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - - } - }); - } - } else { - mProgressDialog.setMessage(otaStatusResponse.status + ":" + otaStatusResponse.msg); - mProgressDialog.getButton(ProgressDialog.BUTTON_POSITIVE).setVisibility(View.VISIBLE); - mProgressDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - - } - }); - } - } - - @Override - public void failure(RetrofitError error) { - Log.e(TAG, "error:" + error); - mProgressDialog.dismiss(); - } - } + iot.otaStatus(new Callback() { + @Override + public void success(OtaStatusResponse otaStatusResponse, Response response) { + if (otaStatusResponse.ota_status.equals("going")) { + displayStatus(node_key); + mProgressDialog.setMessage(otaStatusResponse.ota_msg); + } else if (otaStatusResponse.ota_status.equals("done")) { + mProgressDialog.dismiss(); + + Message message = Message.obtain(); + message.what = MESSAGE_UPDATE_DONE; + message.obj = otaStatusResponse.ota_msg; + mHandler.sendMessage(message); + + } else if (otaStatusResponse.ota_status.equals("error")) { + mProgressDialog.setMessage(otaStatusResponse.ota_status + ":" + otaStatusResponse.ota_msg); + mProgressDialog.getButton(ProgressDialog.BUTTON_POSITIVE).setVisibility(View.VISIBLE); + mProgressDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + + } + }); + } + } + + @Override + public void failure(RetrofitError error) { + mProgressDialog.setMessage(error.getLocalizedMessage()); + mProgressDialog.getButton(ProgressDialog.BUTTON_POSITIVE).setVisibility(View.VISIBLE); + mProgressDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + + } + }); + } + } ); } @@ -440,17 +415,40 @@ public void onItemClick(View view, int position) { List inputGroves = new ArrayList(); List outputGroves = new ArrayList(); + List gpioGroves = new ArrayList(); + List analogGroves = new ArrayList(); + List uartGroves = new ArrayList(); + List i2cGroves = new ArrayList(); + List eventGroves = new ArrayList(); if (mGroveDrivers == null) return; for (GroverDriver g : mGroveDrivers) { - if (!g.Inputs.isEmpty()) { + if (!g.Writes.isEmpty()) { outputGroves.add(g); } - if (!g.Outputs.isEmpty()) + if (!g.Reads.isEmpty()) { inputGroves.add(g); + } + if (g.HasEvent) { + eventGroves.add(g); + } + switch (g.InterfaceType) { + case "GPIO": + gpioGroves.add(g); + break; + case "ANALOG": + analogGroves.add(g); + break; + case "UART": + uartGroves.add(g); + break; + case "I2C": + i2cGroves.add(g); + break; + } } mGroveTypeListAdapter.updateSelection(position); @@ -461,6 +459,16 @@ public void onItemClick(View view, int position) { updateGroveListAdapter(inputGroves); } else if (groveType.equals("Output")) { updateGroveListAdapter(outputGroves); + }else if (groveType.equals("GPIO")) { + updateGroveListAdapter(gpioGroves); + }else if (groveType.equals("ANALOG")) { + updateGroveListAdapter(analogGroves); + }else if (groveType.equals("UART")) { + updateGroveListAdapter(uartGroves); + }else if (groveType.equals("I2C")) { + updateGroveListAdapter(i2cGroves); + }else if (groveType.equals("EVENT")) { + updateGroveListAdapter(eventGroves); } } @@ -655,8 +663,8 @@ else if (pinConfig.position == 6) removePinConfig(position); } else if (event.getClipDescription().hasMimeType(GROVE_REMOVE_PIN6)) { PinConfig pinConfig = (PinConfig) event.getLocalState(); - Log.e(TAG, pinConfig.groveInstanceName); - removePinConfig(pinConfig.groveInstanceName); +// Log.e(TAG, pinConfig.sku); + removePinConfig(pinConfig.sku); Message message = Message.obtain(); message.what = RMV_I2C_GROVE; @@ -687,10 +695,10 @@ private void removePinConfig(int position) { pinConfigs.remove(rp); } - private void removePinConfig(String groveInstanceName) { + private void removePinConfig(String sku) { PinConfig rp = new PinConfig(); for (PinConfig p : pinConfigs) { - if (p.groveInstanceName.equals(groveInstanceName)) + if (p.sku.equals(sku)) rp = p; } pinConfigs.remove(rp); @@ -782,19 +790,22 @@ private void getGrovesData() { String token = user.user_key; api.setAccessToken(token); IotService iot = api.getService(); - iot.scanDrivers(new Callback>() { + iot.scanDrivers(new Callback() { @Override - public void success(List groverDrivers, retrofit.client.Response response) { - for (GroverDriver groveDriver : groverDrivers) { + public void success(GroveDriverListResponse groveDriverListResponse, Response response) { + for (GroverDriver groveDriver : groveDriverListResponse.drivers) { groveDriver.save(); } List g = DBHelper.getGrovesAll(); + for (GroverDriver s : g) { + Log.e(TAG, s.Reads.toString()); + } updateGroveListAdapter(g); } @Override public void failure(RetrofitError error) { - Log.e(TAG, error.toString()); + Log.e(TAG, error.getLocalizedMessage()); } }); } diff --git a/android/app/src/main/java/cc/seeed/iot/ui_setnode/model/NodeConfigHelper.java b/android/app/src/main/java/cc/seeed/iot/ui_setnode/model/NodeConfigHelper.java index b986383..ccc8431 100644 --- a/android/app/src/main/java/cc/seeed/iot/ui_setnode/model/NodeConfigHelper.java +++ b/android/app/src/main/java/cc/seeed/iot/ui_setnode/model/NodeConfigHelper.java @@ -2,11 +2,16 @@ import android.util.Log; +import com.google.gson.Gson; + import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import cc.seeed.iot.util.DBHelper; import cc.seeed.iot.webapi.model.GroverDriver; +import cc.seeed.iot.webapi.model.NodeJson; import cc.seeed.iot.yaml.IotYaml; /** @@ -97,4 +102,39 @@ public static String getConfigYaml(List pinConfigs) { } return y; } + + public static NodeJson getConfigJson(List pinConfigs) { + NodeJson nodeJson = new NodeJson(); + nodeJson.board_name = "Wio Link v1.0"; + List> connections = new ArrayList<>(); + for (PinConfig p : pinConfigs) { + if (p.selected) { + Map map = new HashMap<>(); + switch (p.position) { + case 1: + map.put("port", "D0"); + break; + case 2: + map.put("port", "D1"); + break; + case 3: + map.put("port", "D2"); + break; + case 4: + map.put("port", "A0"); + break; + case 5: + map.put("port", "UART0"); + break; + case 6: + map.put("port","I2C0"); + break; + } + map.put("sku", p.sku); + connections.add(map); + } + } + nodeJson.connections = connections; + return nodeJson; + } } diff --git a/android/app/src/main/java/cc/seeed/iot/ui_smartconfig/ConfigNodeListActivity.java b/android/app/src/main/java/cc/seeed/iot/ui_smartconfig/ConfigNodeListActivity.java deleted file mode 100644 index 473a4d0..0000000 --- a/android/app/src/main/java/cc/seeed/iot/ui_smartconfig/ConfigNodeListActivity.java +++ /dev/null @@ -1,166 +0,0 @@ -package cc.seeed.iot.ui_smartconfig; - -import android.app.ProgressDialog; -import android.content.Context; -import android.net.wifi.WifiInfo; -import android.net.wifi.WifiManager; -import android.os.AsyncTask; -import android.os.Handler; -import android.support.v4.widget.SwipeRefreshLayout; -import android.support.v7.app.AppCompatActivity; -import android.os.Bundle; -import android.support.v7.widget.LinearLayoutManager; -import android.support.v7.widget.RecyclerView; -import android.support.v7.widget.Toolbar; -import android.util.Log; -import android.view.MenuItem; - -import java.io.IOException; -import java.net.SocketTimeoutException; -import java.util.ArrayList; - -import cc.seeed.iot.R; -import cc.seeed.iot.udp.ConfigNodeData; -import cc.seeed.iot.udp.ConfigUdpSocket; - - -public class ConfigNodeListActivity extends AppCompatActivity { - private Toolbar mToolbar; - private RecyclerView mNodeListView; - private SwipeRefreshLayout mSwipeRefreshLayout; - private ConfigNodeListRecyclerAdapter mNodeListAdapter; - private ConfigUdpSocket udpClient; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.config_node_list); - udpClient = new ConfigUdpSocket(); - - Log.e("iot", "ip:" + getLocalBroadcastAddress()); - - mToolbar = (Toolbar) findViewById(R.id.toolbar); - setSupportActionBar(mToolbar); - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - getSupportActionBar().setTitle("WIFI Iot Node"); - - mNodeListView = (RecyclerView) findViewById(R.id.config_nodes_list); - if (mNodeListView != null) { - mNodeListView.setHasFixedSize(true); - LinearLayoutManager layoutManager = new LinearLayoutManager(this); - layoutManager.setOrientation(LinearLayoutManager.VERTICAL); - mNodeListView.setLayoutManager(layoutManager); - - - } - - mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.config_nodes_swipe_refresh); - mSwipeRefreshLayout.setColorSchemeResources(R.color.orange, R.color.green, R.color.blue); - mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { - @Override - public void onRefresh() { - new Handler().postDelayed(new Runnable() { - @Override - public void run() { - new searchConfigNode().execute(); - mSwipeRefreshLayout.setRefreshing(false); - } - }, 0); - } - }); - - new searchConfigNode().execute(); - - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - int id = item.getItemId(); - if (id == android.R.id.home) { - onBackPressed(); - return true; - } - return super.onOptionsItemSelected(item); - } - - - @Override - public void onBackPressed() { - super.onBackPressed(); - } - - private void setupAdapter(ArrayList localNodes) { - mNodeListAdapter = new ConfigNodeListRecyclerAdapter(localNodes); - mNodeListView.setAdapter(mNodeListAdapter); - - } - - - private class searchConfigNode extends AsyncTask> { - //todo: real-time refresh - private ProgressDialog mProgressDialog; - - - @Override - protected void onPreExecute() { - mProgressDialog = new ProgressDialog(ConfigNodeListActivity.this); -// mProgressDialog.setMessage("search node..."); - mProgressDialog.setTitle("Search node..."); - mProgressDialog.setCanceledOnTouchOutside(false); - mProgressDialog.show(); - } - - @Override - protected ArrayList doInBackground(String... params) { - ArrayList configNodeDatas = new ArrayList<>(); - udpClient.setSoTimeout(6000); //3s timeout //todo: long wait - udpClient.sendData(ConfigUdpSocket.CMD_BLANK, getLocalBroadcastAddress()); - while (true) { - try { - ConfigNodeData configNodeData = udpClient.receiveNodeData(); - if (configNodeData != null && !configNodeDatas.contains(configNodeData)) { - configNodeDatas.add(configNodeData); - } - } catch (SocketTimeoutException e) { - break; - } catch (IOException e) { - Log.e("iot", "Error[AsyIO]:" + e); - } - } - - Log.i("iot", "configNodeDatas: " + configNodeDatas); - return configNodeDatas; - } - - @Override - protected void onPostExecute(ArrayList configNodeDatas) { - setupAdapter(configNodeDatas); - mProgressDialog.dismiss(); - } - } - - @Override - protected void onDestroy() { - super.onDestroy(); - udpClient.closeSocket(); - } - - private String getLocalIpAddress() { - WifiManager wifiMan = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); - WifiInfo wifiInf = wifiMan.getConnectionInfo(); - int ipAddress = wifiInf.getIpAddress(); - String ip = String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff), - (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff)); - return ip; - } - - private String getLocalBroadcastAddress() { - String localIpAddress = getLocalIpAddress(); - if (localIpAddress.isEmpty()) - return ""; - String[] ip = localIpAddress.split("\\."); - return ip[0] + "." + ip[1] + "." + ip[2] + ".255"; - } - -} - diff --git a/android/app/src/main/java/cc/seeed/iot/ui_smartconfig/ConfigNodeListRecyclerAdapter.java b/android/app/src/main/java/cc/seeed/iot/ui_smartconfig/ConfigNodeListRecyclerAdapter.java deleted file mode 100755 index 3367f7c..0000000 --- a/android/app/src/main/java/cc/seeed/iot/ui_smartconfig/ConfigNodeListRecyclerAdapter.java +++ /dev/null @@ -1,89 +0,0 @@ -package cc.seeed.iot.ui_smartconfig; - -import android.content.Context; -import android.content.Intent; -import android.support.design.widget.Snackbar; -import android.support.v7.widget.RecyclerView; -import android.util.SparseBooleanArray; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import java.util.ArrayList; - -import cc.seeed.iot.udp.ConfigNodeData; -import cc.seeed.iot.ui_setnode.GroveFilterRecyclerAdapter; -import cc.seeed.iot.R; - -/** - * Created by tenwong on 15/6/25. - */ -public class ConfigNodeListRecyclerAdapter extends RecyclerView.Adapter { - private ArrayList localNodes; - private Context context; - - SparseBooleanArray selector; - private GroveFilterRecyclerAdapter.MainViewHolder.MyItemClickListener mItemClickListener; - - public ConfigNodeListRecyclerAdapter(ArrayList localNodes) { - this.localNodes = localNodes; - } - - @Override - public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - this.context = parent.getContext(); - View v = LayoutInflater.from(parent.getContext()) - .inflate(R.layout.config_node_list_item, parent, false); - - return new MainViewHolder(v); - } - - @Override - public void onBindViewHolder(MainViewHolder holder, final int position) { - final ConfigNodeData localNode = localNodes.get(position); - holder.mMacView.setText(localNode.mac); - holder.mIpView.setText(localNode.ip); - - holder.mView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - Snackbar.make(v, "Todo:set node" + position, Snackbar.LENGTH_SHORT).show(); - - Intent intent = new Intent(context, SetNodeNameActivity.class); - intent.putExtra(SetNodeNameActivity.NODE_LOCAL_IP_ADDRESS, localNode.ip); - context.startActivity(intent); - } - }); - } - - public void selectItem(int position) { - notifyDataSetChanged(); - } - - - public void clearSelectItem() { - notifyDataSetChanged(); - } - - @Override - public int getItemCount() { - return localNodes.size(); - } - - public static class MainViewHolder extends RecyclerView.ViewHolder { - TextView mMacView; - TextView mIpView; - View mView; - - public MainViewHolder(View itemView) { - super(itemView); - mView = itemView; - mMacView = (TextView) itemView.findViewById(R.id.txtvmac); - mIpView = (TextView) itemView.findViewById(R.id.txtvip); - - } - - } - -} diff --git a/android/app/src/main/java/cc/seeed/iot/ui_smartconfig/EspWifiAdminSimple.java b/android/app/src/main/java/cc/seeed/iot/ui_smartconfig/EspWifiAdminSimple.java deleted file mode 100644 index 3d34a1e..0000000 --- a/android/app/src/main/java/cc/seeed/iot/ui_smartconfig/EspWifiAdminSimple.java +++ /dev/null @@ -1,67 +0,0 @@ -package cc.seeed.iot.ui_smartconfig; - -import android.content.Context; -import android.net.ConnectivityManager; -import android.net.NetworkInfo; -import android.net.wifi.WifiInfo; -import android.net.wifi.WifiManager; - -public class EspWifiAdminSimple { - - private final Context mContext; - - - public EspWifiAdminSimple(Context context) { - mContext = context; - } - - public String getWifiConnectedSsid() { - WifiInfo mWifiInfo = getConnectionInfo(); - String ssid = null; - if (mWifiInfo != null && isWifiConnected()) { - int len = mWifiInfo.getSSID().length(); - if (mWifiInfo.getSSID().startsWith("\"") - && mWifiInfo.getSSID().endsWith("\"")) { - ssid = mWifiInfo.getSSID().substring(1, len - 1); - } else { - ssid = mWifiInfo.getSSID(); - } - - } - return ssid; - } - - public String getWifiConnectedBssid() { - WifiInfo mWifiInfo = getConnectionInfo(); - String bssid = null; - if (mWifiInfo != null && isWifiConnected()) { - bssid = mWifiInfo.getBSSID(); - } - return bssid; - } - - // get the wifi info which is "connected" in wifi-setting - private WifiInfo getConnectionInfo() { - WifiManager mWifiManager = (WifiManager) mContext - .getSystemService(Context.WIFI_SERVICE); - WifiInfo wifiInfo = mWifiManager.getConnectionInfo(); - return wifiInfo; - } - - private boolean isWifiConnected() { - NetworkInfo mWiFiNetworkInfo = getWifiNetworkInfo(); - boolean isWifiConnected = false; - if (mWiFiNetworkInfo != null) { - isWifiConnected = mWiFiNetworkInfo.isConnected(); - } - return isWifiConnected; - } - - private NetworkInfo getWifiNetworkInfo() { - ConnectivityManager mConnectivityManager = (ConnectivityManager) mContext - .getSystemService(Context.CONNECTIVITY_SERVICE); - NetworkInfo mWiFiNetworkInfo = mConnectivityManager - .getNetworkInfo(ConnectivityManager.TYPE_WIFI); - return mWiFiNetworkInfo; - } -} diff --git a/android/app/src/main/java/cc/seeed/iot/ui_smartconfig/GoReadyActivity.java b/android/app/src/main/java/cc/seeed/iot/ui_smartconfig/GoReadyActivity.java deleted file mode 100644 index da0d91c..0000000 --- a/android/app/src/main/java/cc/seeed/iot/ui_smartconfig/GoReadyActivity.java +++ /dev/null @@ -1,108 +0,0 @@ -package cc.seeed.iot.ui_smartconfig; - -import android.app.ProgressDialog; -import android.content.Context; -import android.content.Intent; -import android.net.wifi.WifiManager; -import android.os.Bundle; -import android.support.v7.app.AppCompatActivity; -import android.support.v7.widget.Toolbar; -import android.view.MenuItem; -import android.view.View; -import android.widget.Button; -import android.widget.Toast; - -import cc.seeed.iot.MyApplication; -import cc.seeed.iot.datastruct.User; -import cc.seeed.iot.webapi.IotApi; -import cc.seeed.iot.webapi.IotService; -import cc.seeed.iot.R; -import cc.seeed.iot.ui_ap_config.WifiWioListActivity; -import cc.seeed.iot.webapi.model.NodeResponse; -import retrofit.Callback; -import retrofit.RetrofitError; -import retrofit.client.Response; - -public class GoReadyActivity extends AppCompatActivity { - public Toolbar mToolbar; - public Button mGoReadyButtonView; - - private String node_sn; - private String node_key; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.smartconfig_ready); - - mToolbar = (Toolbar) findViewById(R.id.toolbar); - setSupportActionBar(mToolbar); - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - getSupportActionBar().setTitle("WIFI Iot Node"); - - - mGoReadyButtonView = (Button) findViewById(R.id.smartconfig_ready_btn); - mGoReadyButtonView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - - attemptLogin("node000"); - WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); - wifiManager.startScan(); - } - }); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - int id = item.getItemId(); - - if (id == android.R.id.home) { - onBackPressed(); - return true; - } - return super.onOptionsItemSelected(item); - } - - @Override - public void onBackPressed() { - super.onBackPressed(); - } - - private void attemptLogin(final String node_name) { - final ProgressDialog mProgressBar = new ProgressDialog(this); - - mProgressBar.setMessage("connect server..."); - mProgressBar.show(); - IotApi api = new IotApi(); - User user = ((MyApplication) getApplication()).getUser(); - 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 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_smartconfig/SetNodeNameActivity.java b/android/app/src/main/java/cc/seeed/iot/ui_smartconfig/SetNodeNameActivity.java deleted file mode 100644 index 66bf6c9..0000000 --- a/android/app/src/main/java/cc/seeed/iot/ui_smartconfig/SetNodeNameActivity.java +++ /dev/null @@ -1,195 +0,0 @@ -package cc.seeed.iot.ui_smartconfig; - -import android.app.ProgressDialog; -import android.content.Intent; -import android.os.AsyncTask; -import android.os.Bundle; -import android.support.v7.app.AppCompatActivity; -import android.support.v7.widget.Toolbar; -import android.util.Log; -import android.view.MenuItem; -import android.view.View; -import android.view.WindowManager; -import android.widget.Button; -import android.widget.EditText; -import android.widget.Toast; - -import java.io.IOException; -import java.net.SocketTimeoutException; - -import cc.seeed.iot.MyApplication; -import cc.seeed.iot.datastruct.User; -import cc.seeed.iot.udp.ConfigUdpSocket; -import cc.seeed.iot.ui_main.MainScreenActivity; -import cc.seeed.iot.webapi.IotApi; -import cc.seeed.iot.webapi.IotService; -import cc.seeed.iot.webapi.model.Node; -import cc.seeed.iot.webapi.model.NodeResponse; -import cc.seeed.iot.R; -import retrofit.Callback; -import retrofit.RetrofitError; -import retrofit.client.Response; - -public class SetNodeNameActivity extends AppCompatActivity { - public static final String NODE_LOCAL_IP_ADDRESS = "node.local.ip.address"; - public Toolbar mToolbar; - public EditText mNodeNameView; - public Button mGoPlayButtonView; - private ConfigUdpSocket udpClient; - private Intent intent; - private String ip; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.smartconfig_connected); - - getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); - - intent = getIntent(); - ip = intent.getStringExtra(NODE_LOCAL_IP_ADDRESS); - - udpClient = new ConfigUdpSocket(); - - mToolbar = (Toolbar) findViewById(R.id.toolbar); - setSupportActionBar(mToolbar); - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - getSupportActionBar().setTitle("WIFI Iot Node"); - - mNodeNameView = (EditText) findViewById(R.id.add_node_name); - - mGoPlayButtonView = (Button) findViewById(R.id.first_time_how_to_api_key); - mGoPlayButtonView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - String node_name = mNodeNameView.getText().toString(); - attemptLogin(node_name); - } - }); - - } - - private void GoSetNodeSn(Node node) { - - if (node == null) - return; - - String cmd_set_sn = "KeySN: " + node.node_key + "," + node.node_sn; - - Log.i("iot", "cmd_sn: " + cmd_set_sn); - Log.i("iot", "ip: " + ip); - - new SetNodeSn().execute(cmd_set_sn, ip); - } - - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - int id = item.getItemId(); - - if (id == android.R.id.home) { - onBackPressed(); - return true; - } - return super.onOptionsItemSelected(item); - } - - @Override - public void onBackPressed() { - super.onBackPressed(); - } - - private void attemptLogin(final String node_name) { - final Node node = new Node(); - boolean cancel = false; - View focusView = null; - - final ProgressDialog mProgressBar = new ProgressDialog(this); - - if (cancel) { - focusView.requestFocus(); - } else { -// showProgress(true); - mProgressBar.setTitle("connect server..."); - mProgressBar.show(); - IotApi api = new IotApi(); - User user = ((MyApplication) getApplication()).getUser(); - 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.name = node_name; - node.node_key = nodeResponse.node_key; - node.node_sn = nodeResponse.node_sn; - - GoSetNodeSn(node); - } else { -// showProgress(false); - mProgressBar.dismiss(); - mNodeNameView.setError(nodeResponse.msg); - mNodeNameView.requestFocus(); - } - } - - @Override - public void failure(RetrofitError error) { -// showProgress(false); - mProgressBar.dismiss(); - Toast.makeText(SetNodeNameActivity.this, "Connect server error!", Toast.LENGTH_LONG).show(); - } - }); - } - } - - private class SetNodeSn extends AsyncTask { - //todo: real-time refresh - private ProgressDialog mProgressDialog; - - @Override - protected void onPreExecute() { - mProgressDialog = new ProgressDialog(SetNodeNameActivity.this); -// mProgressDialog.setMessage("search node..."); - mProgressDialog.setTitle("Set node_sn..."); - mProgressDialog.setCanceledOnTouchOutside(false); - mProgressDialog.show(); - } - - @Override - protected Boolean doInBackground(String... params) { - String cmd = params[0]; - String ipAddr = params[1]; - udpClient.setSoTimeout(1000); //1s timeout - udpClient.sendData(cmd, ipAddr); - for (int i = 0; i < 3; i++) { - try { - byte[] bytes = udpClient.receiveData(); - if (new String(bytes).substring(0, 1 + 1).equals("ok")) { - Log.e("iot", "set Node Success"); - //todo: upda ui is success - break; - } - } catch (SocketTimeoutException e) { - udpClient.setSoTimeout(3000); - udpClient.sendData(cmd, ipAddr); - continue; - } catch (IOException e) { - Log.e("iot", "Error[AsyIO]:" + e); - } - } - return true; - } - - @Override - protected void onPostExecute(Boolean b) { - mProgressDialog.dismiss(); - Intent intent = new Intent(SetNodeNameActivity.this, MainScreenActivity.class); - intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); - startActivity(intent); - } - } -} diff --git a/android/app/src/main/java/cc/seeed/iot/ui_smartconfig/SmartConnectActivity.java b/android/app/src/main/java/cc/seeed/iot/ui_smartconfig/SmartConnectActivity.java deleted file mode 100644 index e47b30d..0000000 --- a/android/app/src/main/java/cc/seeed/iot/ui_smartconfig/SmartConnectActivity.java +++ /dev/null @@ -1,246 +0,0 @@ -package cc.seeed.iot.ui_smartconfig; - -import android.app.ProgressDialog; -import android.content.DialogInterface; -import android.content.Intent; -import android.os.AsyncTask; -import android.os.Bundle; -import android.support.design.widget.Snackbar; -import android.support.v7.app.AppCompatActivity; -import android.support.v7.widget.Toolbar; -import android.text.TextUtils; -import android.util.Log; -import android.view.MenuItem; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.WindowManager; -import android.widget.Button; -import android.widget.EditText; -import android.widget.TextView; - -import java.util.List; - -import cc.seeed.iot.MyApplication; -import cc.seeed.iot.esptouch.EsptouchTask; -import cc.seeed.iot.esptouch.IEsptouchResult; -import cc.seeed.iot.esptouch.IEsptouchTask; -import cc.seeed.iot.esptouch.task.__IEsptouchTask; -import cc.seeed.iot.R; -import cc.seeed.iot.ui_main.MainScreenActivity; - -public class SmartConnectActivity extends AppCompatActivity implements OnClickListener { - private static final String TAG = "IOT"; - public Toolbar mToolbar; - public TextView mSssidView; - public EditText mPasswordView; - public Button mConnectBtnView; - private EspWifiAdminSimple mWifiAdmin; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.smartconfig_connect); - getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); - - mToolbar = (Toolbar) findViewById(R.id.toolbar); - setSupportActionBar(mToolbar); - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - getSupportActionBar().setTitle("WIFI Iot Node"); - - mSssidView = (TextView) findViewById(R.id.ssid); - mPasswordView = (EditText) findViewById(R.id.wifi_password); - mConnectBtnView = (Button) findViewById(R.id.first_time_how_to_api_key); - mConnectBtnView.setOnClickListener(this); - - mWifiAdmin = new EspWifiAdminSimple(this); - } - - @Override - protected void onResume() { - super.onResume(); - // display the connected ap's ssid - String apSsid = mWifiAdmin.getWifiConnectedSsid(); - if (apSsid != null) { - mSssidView.setText(apSsid); - } else { - mSssidView.setText(""); - } - // check whether the wifi is connected - boolean isApSsidEmpty = TextUtils.isEmpty(apSsid); - mConnectBtnView.setEnabled(!isApSsidEmpty); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - int id = item.getItemId(); - - if (id == android.R.id.home) { - onBackPressed(); - return true; - } - return super.onOptionsItemSelected(item); - } - - @Override - public void onBackPressed() { - super.onBackPressed(); - } - - @Override - public void onClick(View v) { - - if (v == mConnectBtnView) { - String apSsid = mSssidView.getText().toString(); - String apPassword = mPasswordView.getText().toString(); - String apBssid = mWifiAdmin.getWifiConnectedBssid(); -// Boolean isSsidHidden = mSwitchIsSsidHidden.isChecked(); //todo: add hidden view - Boolean isSsidHidden = false; - String isSsidHiddenStr = "NO"; -// String taskResultCountStr = Integer.toString(mSpinnerTaskCount -// .getSelectedItemPosition()); //todo: what means taskCount? - String taskResultCountStr = "1"; - if (isSsidHidden) { - isSsidHiddenStr = "YES"; - } - if (__IEsptouchTask.DEBUG) { - Log.d(TAG, "mBtnConfirm is clicked, mEdtApSsid = " + apSsid - + ", " + " mEdtApPassword = " + apPassword); - } - new EsptouchAsyncTask3().execute(apSsid, apBssid, apPassword, - isSsidHiddenStr, taskResultCountStr); - } - } - - private class EsptouchAsyncTask3 extends AsyncTask> { - - private ProgressDialog mProgressDialog; - - private IEsptouchTask mEsptouchTask; - // without the lock, if the user tap confirm and cancel quickly enough, - // the bug will arise. the reason is follows: - // 0. task is starting created, but not finished - // 1. the task is cancel for the task hasn't been created, it do nothing - // 2. task is created - // 3. Oops, the task should be cancelled, but it is running - private final Object mLock = new Object(); - - @Override - protected void onPreExecute() { - mProgressDialog = new ProgressDialog(SmartConnectActivity.this); - mProgressDialog - .setMessage("Esptouch is configuring, please wait for a moment..."); - mProgressDialog.setCanceledOnTouchOutside(false); - mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { - @Override - public void onCancel(DialogInterface dialog) { - synchronized (mLock) { - if (__IEsptouchTask.DEBUG) { - Log.i(TAG, "progress dialog is canceled"); - } - if (mEsptouchTask != null) { - mEsptouchTask.interrupt(); - } - } - } - }); - mProgressDialog.setButton(DialogInterface.BUTTON_POSITIVE, - "Waiting...", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - } - }); - mProgressDialog.show(); - mProgressDialog.getButton(DialogInterface.BUTTON_POSITIVE) - .setEnabled(false); - } - - @Override - protected List doInBackground(String... params) { - int taskResultCount = -1; - synchronized (mLock) { - String apSsid = params[0]; - String apBssid = params[1]; - String apPassword = params[2]; - String isSsidHiddenStr = params[3]; - String taskResultCountStr = params[4]; - boolean isSsidHidden = false; - if (isSsidHiddenStr.equals("YES")) { - isSsidHidden = true; - } - taskResultCount = Integer.parseInt(taskResultCountStr); - mEsptouchTask = new EsptouchTask(apSsid, apBssid, apPassword, - isSsidHidden, SmartConnectActivity.this); - } - List resultList = mEsptouchTask.executeForResults(taskResultCount); - return resultList; - } - - @Override - protected void onPostExecute(List result) { - mProgressDialog.getButton(DialogInterface.BUTTON_POSITIVE) - .setEnabled(true); - mProgressDialog.getButton(DialogInterface.BUTTON_POSITIVE). - setText("Confirm"); - IEsptouchResult firstResult = result.get(0); - // check whether the task is cancelled and no results received - if (!firstResult.isCancelled()) { - int count = 0; - // max results to be displayed, if it is more than maxDisplayCount, - // just show the count of redundant ones - final int maxDisplayCount = 5; - // the task received some results including cancelled while - // executing before receiving enough results - if (firstResult.isSuc()) { - StringBuilder sb = new StringBuilder(); - for (IEsptouchResult resultInList : result) { - sb.append("Esptouch success, bssid = " - + resultInList.getBssid() - + ",InetAddress = " - + resultInList.getInetAddress() - .getHostAddress() + "\n"); - count++; - if (count >= maxDisplayCount) { - break; - } - } - if (count < result.size()) { - sb.append("\nthere's " + (result.size() - count) - + " more result(s) without showing\n"); - } - mProgressDialog.setMessage(sb.toString()); - mProgressDialog.getButton(DialogInterface.BUTTON_POSITIVE). - setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - nextActivity(); - mProgressDialog.dismiss(); - } - }); - - } else { - mProgressDialog.setMessage("Esptouch fail"); - mProgressDialog.getButton(DialogInterface.BUTTON_POSITIVE). - setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - Snackbar.make(v, "todo: reconnect node!", Snackbar.LENGTH_SHORT).show(); - mProgressDialog.dismiss(); - } - }); - } - } - } - } - - - private void nextActivity() { - if (((MyApplication) getApplication()).getConfigState()) { - Intent intent = new Intent(SmartConnectActivity.this, ConfigNodeListActivity.class); - startActivity(intent); - } else { - Intent intent = new Intent(SmartConnectActivity.this, MainScreenActivity.class); - intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); - startActivity(intent); - } - } -} diff --git a/android/app/src/main/java/cc/seeed/iot/util/Util.java b/android/app/src/main/java/cc/seeed/iot/util/Util.java deleted file mode 100644 index 642edb1..0000000 --- a/android/app/src/main/java/cc/seeed/iot/util/Util.java +++ /dev/null @@ -1,13 +0,0 @@ -package cc.seeed.iot.util; - -import android.content.Context; - -/** - * Created by tenwong on 15/10/20. - */ -public class Util { - public static boolean checkIsChina(Context context) { - return context.getResources().getConfiguration().locale.getCountry().equals("CN"); - } - -} diff --git a/android/app/src/main/java/cc/seeed/iot/util/UtilMapSerializer.java b/android/app/src/main/java/cc/seeed/iot/util/UtilMapSerializer.java index 84f8699..ffbde07 100644 --- a/android/app/src/main/java/cc/seeed/iot/util/UtilMapSerializer.java +++ b/android/app/src/main/java/cc/seeed/iot/util/UtilMapSerializer.java @@ -4,11 +4,12 @@ import com.activeandroid.serializer.TypeSerializer; import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; -import java.lang.reflect.Type; +import org.json.JSONException; +import org.json.JSONObject; + import java.util.HashMap; -import java.util.List; +import java.util.Iterator; import java.util.Map; /** @@ -30,25 +31,30 @@ public String serialize(Object o) { if (o == null) { return null; } - Gson gson = new Gson(); - Map> map = (Map>) o; + Map map = (Map) o; String json = gson.toJson(map); +// Log.e("Map", json); return json; } @Override - public Map> deserialize(Object o) { + public Map deserialize(Object o) { if (o == null) { return null; } - Gson gson = new Gson(); - Map> map = new HashMap>(); - - Type type = new TypeToken>>() { - }.getType(); + Map map = new HashMap<>(); + + try { + JSONObject json = new JSONObject((String) o); + for (Iterator it = json.keys(); it.hasNext(); ) { + String key = (String) it.next(); + map.put(key, json.get(key)); + } + } catch (JSONException e) { + e.printStackTrace(); + } - map = gson.fromJson((String) o, type); return map; } } diff --git a/android/app/src/main/java/cc/seeed/iot/webapi/CustomErrorHandler.java b/android/app/src/main/java/cc/seeed/iot/webapi/CustomErrorHandler.java new file mode 100644 index 0000000..da4e199 --- /dev/null +++ b/android/app/src/main/java/cc/seeed/iot/webapi/CustomErrorHandler.java @@ -0,0 +1,38 @@ +package cc.seeed.iot.webapi; + +import android.util.Log; + +import cc.seeed.iot.webapi.model.ErrorResponse; +import retrofit.ErrorHandler; +import retrofit.RetrofitError; + +/** + * Created by tenwong on 15/12/28. + */ +public class CustomErrorHandler implements ErrorHandler { + private static String TAG = "CustomErrorHandler"; + + @Override + public Throwable handleError(RetrofitError cause) { + String errorDescription; + + if (cause.isNetworkError()) { + errorDescription = "connect server failure!"; + } else { + if (cause.getResponse() == null) { + errorDescription = "no response!"; + } else { + + // Error message handling - return a simple error to Retrofit handlers.. + try { + ErrorResponse errorResponse = (ErrorResponse) cause.getBodyAs(ErrorResponse.class); + errorDescription = errorResponse.error; + } catch (Exception ex) { + errorDescription = "Exception error!"; + } + } + } + + return new Exception(errorDescription); + } +} \ No newline at end of file diff --git a/android/app/src/main/java/cc/seeed/iot/webapi/ExchangeApi.java b/android/app/src/main/java/cc/seeed/iot/webapi/ExchangeApi.java deleted file mode 100755 index d27985f..0000000 --- a/android/app/src/main/java/cc/seeed/iot/webapi/ExchangeApi.java +++ /dev/null @@ -1,136 +0,0 @@ -package cc.seeed.iot.webapi; - -import com.google.gson.GsonBuilder; -import com.squareup.okhttp.OkHttpClient; - -import java.lang.reflect.Modifier; -import java.security.cert.CertificateException; -import java.util.concurrent.Executor; -import java.util.concurrent.Executors; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; - -import retrofit.RequestInterceptor; -import retrofit.RestAdapter; -import retrofit.android.MainThreadExecutor; -import retrofit.client.OkClient; -import retrofit.converter.GsonConverter; - -//import cc.seeed.iot.storge.MySharedPreference; - -/** - * Created by tenwong on 15/6/23. - */ -public class ExchangeApi { - private static String data_exchange_url = ""; - private final IotService mIotService; - private String mAccessToken; - -// public IotApi(Executor httpExecutor, Executor callbackExecutor) { -// mIotService = init(httpExecutor, callbackExecutor); -// } - - public static void SetServerUrl(String url) { - data_exchange_url = url; - } - - public ExchangeApi() { - - Executor httpExecutor = Executors.newSingleThreadExecutor(); - MainThreadExecutor callbackExecutor = new MainThreadExecutor(); - mIotService = init(httpExecutor, callbackExecutor); - } - - - private IotService init(Executor httpExecutor, Executor callbackExecutor) { - OkHttpClient client = getUnsafeOkHttpClient(); - final RestAdapter restAdapter = new RestAdapter.Builder() - .setLogLevel(RestAdapter.LogLevel.FULL) - .setExecutors(httpExecutor, callbackExecutor) - .setEndpoint(data_exchange_url) - .setRequestInterceptor(new WebApiAuthenticator()) - .setClient(new OkClient(client)) - .setConverter(new GsonConverter(new GsonBuilder() - .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC) - .serializeNulls() - .create())) - .build(); - - return restAdapter.create(IotService.class); - } - - /** - * Do not check certificate,Todo use keyStore - */ - private static OkHttpClient getUnsafeOkHttpClient() { - try { - // Create a trust manager that does not validate certificate chains - final TrustManager[] trustAllCerts = new TrustManager[]{ - new X509TrustManager() { - @Override - public void checkClientTrusted( - java.security.cert.X509Certificate[] chain, String authType) - throws CertificateException { - } - - @Override - public void checkServerTrusted( - java.security.cert.X509Certificate[] chain, String authType) - throws CertificateException { - } - - @Override - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return null; - } - } - }; - - // Install the all-trusting trust manager - final SSLContext sslContext = SSLContext.getInstance("SSL"); - sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); - // Create an ssl socket factory with our all-trusting manager - final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); - - OkHttpClient okHttpClient = new OkHttpClient(); - okHttpClient.setSslSocketFactory(sslSocketFactory); - okHttpClient.setHostnameVerifier(new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { - return true; - } - }); - - return okHttpClient; - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - - public IotService getService() { - return mIotService; - } - - - public ExchangeApi setAccessToken(String accessToken) { - mAccessToken = accessToken; - return this; - } - - - private class WebApiAuthenticator implements RequestInterceptor { - @Override - public void intercept(RequestFacade request) { - if (mAccessToken != null) { - request.addHeader("Authorization", "token " + mAccessToken); - } - } - } - -} diff --git a/android/app/src/main/java/cc/seeed/iot/webapi/IotApi.java b/android/app/src/main/java/cc/seeed/iot/webapi/IotApi.java index 56209e5..2b466b2 100755 --- a/android/app/src/main/java/cc/seeed/iot/webapi/IotApi.java +++ b/android/app/src/main/java/cc/seeed/iot/webapi/IotApi.java @@ -15,7 +15,6 @@ import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; -import cc.seeed.iot.MyApplication; import retrofit.RequestInterceptor; import retrofit.RestAdapter; import retrofit.android.MainThreadExecutor; @@ -57,6 +56,7 @@ private IotService init(Executor httpExecutor, Executor callbackExecutor) { .setEndpoint(iot_url) .setRequestInterceptor(new WebApiAuthenticator()) .setClient(new OkClient(client)) + .setErrorHandler(new CustomErrorHandler()) .setConverter(new GsonConverter(new GsonBuilder() .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC) .serializeNulls() diff --git a/android/app/src/main/java/cc/seeed/iot/webapi/IotService.java b/android/app/src/main/java/cc/seeed/iot/webapi/IotService.java index 3f0af17..db839fa 100755 --- a/android/app/src/main/java/cc/seeed/iot/webapi/IotService.java +++ b/android/app/src/main/java/cc/seeed/iot/webapi/IotService.java @@ -1,22 +1,21 @@ package cc.seeed.iot.webapi; -import java.util.List; -import java.util.Map; - -import cc.seeed.iot.webapi.model.GroverDriver; +import cc.seeed.iot.webapi.model.GroveDriverListResponse; +import cc.seeed.iot.webapi.model.LoginResponse; +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.OtaStatusResponse; -import cc.seeed.iot.webapi.model.PropertyResponse; -import cc.seeed.iot.webapi.model.CommonResponse; +import cc.seeed.iot.webapi.model.StatusResponse; +import cc.seeed.iot.webapi.model.SuccessResponse; import cc.seeed.iot.webapi.model.UserResponse; -import cc.seeed.iot.webapi.model.WellKnownResponse; import retrofit.Callback; +import retrofit.http.Body; import retrofit.http.GET; import retrofit.http.POST; import retrofit.http.Path; import retrofit.http.Query; -import retrofit.http.QueryMap; /** * Created by tenwong on 15/6/23. @@ -32,15 +31,13 @@ public void userCreate(@Query("email") String email, @Query("password") String p @POST("/v1/user/login") public void userLogin(@Query("email") String email, @Query("password") String password, - Callback callback); + Callback callback); @POST("/v1/user/changepassword") - public void userChangePassword(@Query("password") String newPwd, - @Query("access_token") String user_token, - Callback callback); + public void userChangePassword(@Query("password") String newPwd, Callback callback); @POST("/v1/user/retrievepassword") - public void userRetrievePassword(@Query("email") String email, Callback callback); + public void userRetrievePassword(@Query("email") String email, Callback callback); /** * Node manage APIs @@ -54,56 +51,52 @@ public void userChangePassword(@Query("password") String newPwd, public void nodesList(Callback callback); @POST("/v1/nodes/rename") - public void nodesRename(@Query("name") String node_name, - @Query("node_sn") String node_sn, - Callback callback); + public void nodesRename(@Query("name") String node_name, @Query("node_sn") String node_sn, + Callback callback); - @POST("/v1/node/setting/dataxserver/{ip}") - public void nodeSettingDataxserver(@Path("ip") String property, Callback callback); + @POST("/v1/node/setting/dataxserver/{address}") + public void nodeSettingDataxserver(@Path("address") String property, Callback callback); @POST("/v1/nodes/delete") - public void nodesDelete(@Query("node_sn") String node_sn, Callback callback); + public void nodesDelete(@Query("node_sn") String node_sn, Callback callback); @GET("/v1/node/config") - public void nodeConfig(Callback callback); + public void nodeConfig(Callback callback); - @POST("/v1/user/download") - public void userDownload(@Query("access_token") String node_key, - @Query("yaml") String yaml, - Callback callback); + @POST("/v1/ota/trigger") + public void userDownload(@Body NodeJson nodeJson, Callback callback); - @POST("/v1/ota/status") - public void otaStatus(@Query("access_token") String node_key, - Callback callback); + @GET("/v1/ota/status") + public void otaStatus(Callback callback); /** * Grove driver scanning APIs */ @GET("/v1/scan/drivers") - public void scanDrivers(Callback> callback); + public void scanDrivers(Callback callback); @GET("/v1/scan/status") - public void scanStatus(Callback callback); - - - /** - * Node property call APIs - * Before call, send node_key Authorization, node_key - */ - @GET("/v1/node/.well-known") - public void nodeWellKnown(Callback callback); - - - // node/Grove_Example1/temp - // node/Grove_Example1/with_arg/90 - @GET("/v1/node/{propertyArgs}") - public void readPropertyArg1(@Path("propertyArgs") String property, - Callback callback); - - - // ...-d "a=10&b=10.5&c=445566" https://iot.yuzhe.me/v1/node/Grove_Example1/multi_value - @POST("/v1/node/{property}") - public void writePropert(@Path("property") String property, @QueryMap Map option, - Callback callback); + public void scanStatus(Callback callback); + + +// /** +// * Node property call APIs +// * Before call, send node_key Authorization, node_key +// */ +// @GET("/v1/node/.well-known") +// public void nodeWellKnown(Callback callback); +// +// +// // node/Grove_Example1/temp +// // node/Grove_Example1/with_arg/90 +// @GET("/v1/node/{propertyArgs}") +// public void readPropertyArg1(@Path("propertyArgs") String property, +// Callback callback); +// +// +// // ...-d "a=10&b=10.5&c=445566" https://iot.yuzhe.me/v1/node/Grove_Example1/multi_value +// @POST("/v1/node/{property}") +// public void writePropert(@Path("property") String property, @QueryMap Map option, +// Callback callback); } diff --git a/android/app/src/main/java/cc/seeed/iot/webapi/model/ErrorResponse.java b/android/app/src/main/java/cc/seeed/iot/webapi/model/ErrorResponse.java new file mode 100755 index 0000000..b60df71 --- /dev/null +++ b/android/app/src/main/java/cc/seeed/iot/webapi/model/ErrorResponse.java @@ -0,0 +1,8 @@ +package cc.seeed.iot.webapi.model; + +/** + * Created by tenwong on 15/6/23. + */ +public class ErrorResponse { + public String error; +} diff --git a/android/app/src/main/java/cc/seeed/iot/webapi/model/GroveDriverListResponse.java b/android/app/src/main/java/cc/seeed/iot/webapi/model/GroveDriverListResponse.java new file mode 100755 index 0000000..8482201 --- /dev/null +++ b/android/app/src/main/java/cc/seeed/iot/webapi/model/GroveDriverListResponse.java @@ -0,0 +1,10 @@ +package cc.seeed.iot.webapi.model; + +import java.util.List; + +/** + * Created by tenwong on 15/6/25. + */ +public class GroveDriverListResponse { + public List drivers; +} diff --git a/android/app/src/main/java/cc/seeed/iot/webapi/model/GroverDriver.java b/android/app/src/main/java/cc/seeed/iot/webapi/model/GroverDriver.java index 304d0a9..86aafa7 100755 --- a/android/app/src/main/java/cc/seeed/iot/webapi/model/GroverDriver.java +++ b/android/app/src/main/java/cc/seeed/iot/webapi/model/GroverDriver.java @@ -12,14 +12,11 @@ */ @Table(name = "groves") public class GroverDriver extends Model { - @Column(name = "files") - public List Files; - @Column(name = "sku", unique = true, onUniqueConflict = Column.ConflictAction.REPLACE) public String SKU; - @Column(name = "inputs") - public Map> Inputs; + @Column(name = "files") + public List Files; @Column(name = "class_file") public String ClassFile; @@ -27,36 +24,39 @@ public class GroverDriver extends Model { @Column(name = "grove_name") public String GroveName; - @Column(name = "outputs") - public Map> Outputs; - @Column(name = "image_url") public String ImageURL; -// @Column(name = "events") -// public Map Events; + @Column(name = "writes") + public Map Writes; + + @Column(name = "has_power_off_func") + public Boolean HasPowerOffFunc; @Column(name = "class_name") public String ClassName; + @Column(name = "reads") + public Map Reads; + @Column(name = "can_get_last_error") public Boolean CanGetLastError; - @Column(name = "interface_type") - public String InterfaceType; + @Column(name = "events") + public Map Events; @Column(name = "has_event") public Boolean HasEvent; - @Column(name = "has_power_off_func") - public Boolean HasPowerOffFunc; - - @Column(name = "has_power_on_func") - public Boolean HasPowerOnFunc; + @Column(name = "interface_type") + public String InterfaceType; @Column(name = "include_path") public String IncludePath; + @Column(name = "has_power_on_func") + public Boolean HasPowerOnFunc; + @Column(name = "grove_id") public int ID; diff --git a/android/app/src/main/java/cc/seeed/iot/webapi/model/LoginResponse.java b/android/app/src/main/java/cc/seeed/iot/webapi/model/LoginResponse.java new file mode 100755 index 0000000..14ca0f9 --- /dev/null +++ b/android/app/src/main/java/cc/seeed/iot/webapi/model/LoginResponse.java @@ -0,0 +1,9 @@ +package cc.seeed.iot.webapi.model; + +/** + * Created by tenwong on 15/6/23. + */ +public class LoginResponse { + public String token; + public String user_id; +} diff --git a/android/app/src/main/java/cc/seeed/iot/webapi/model/NodeConfigResponse.java b/android/app/src/main/java/cc/seeed/iot/webapi/model/NodeConfigResponse.java new file mode 100755 index 0000000..d342b0f --- /dev/null +++ b/android/app/src/main/java/cc/seeed/iot/webapi/model/NodeConfigResponse.java @@ -0,0 +1,9 @@ +package cc.seeed.iot.webapi.model; + +/** + * Created by tenwong on 15/6/23. + */ +public class NodeConfigResponse { + public NodeJson config; + public String type; +} diff --git a/android/app/src/main/java/cc/seeed/iot/webapi/model/NodeJson.java b/android/app/src/main/java/cc/seeed/iot/webapi/model/NodeJson.java new file mode 100755 index 0000000..5acd15e --- /dev/null +++ b/android/app/src/main/java/cc/seeed/iot/webapi/model/NodeJson.java @@ -0,0 +1,12 @@ +package cc.seeed.iot.webapi.model; + +import java.util.List; +import java.util.Map; + +/** + * Created by tenwong on 15/6/25. + */ +public class NodeJson { + public String board_name; + public List> connections; +} diff --git a/android/app/src/main/java/cc/seeed/iot/webapi/model/NodeListResponse.java b/android/app/src/main/java/cc/seeed/iot/webapi/model/NodeListResponse.java index b9d83b1..eb979e4 100755 --- a/android/app/src/main/java/cc/seeed/iot/webapi/model/NodeListResponse.java +++ b/android/app/src/main/java/cc/seeed/iot/webapi/model/NodeListResponse.java @@ -5,6 +5,6 @@ /** * Created by tenwong on 15/6/25. */ -public class NodeListResponse extends CommonResponse { +public class NodeListResponse { public List nodes; } diff --git a/android/app/src/main/java/cc/seeed/iot/webapi/model/NodeResponse.java b/android/app/src/main/java/cc/seeed/iot/webapi/model/NodeResponse.java index 3e523f1..55bf099 100755 --- a/android/app/src/main/java/cc/seeed/iot/webapi/model/NodeResponse.java +++ b/android/app/src/main/java/cc/seeed/iot/webapi/model/NodeResponse.java @@ -4,8 +4,6 @@ * Created by tenwong on 15/6/23. */ public class NodeResponse { - public String status; - public String msg; public String node_key; public String node_sn; } diff --git a/android/app/src/main/java/cc/seeed/iot/webapi/model/NodeYaml.java b/android/app/src/main/java/cc/seeed/iot/webapi/model/NodeYaml.java new file mode 100755 index 0000000..6d0d928 --- /dev/null +++ b/android/app/src/main/java/cc/seeed/iot/webapi/model/NodeYaml.java @@ -0,0 +1,12 @@ +package cc.seeed.iot.webapi.model; + +import java.util.List; +import java.util.Map; + +/** + * Created by tenwong on 15/6/25. + */ +public class NodeYaml { + public String config; + public String type; +} diff --git a/android/app/src/main/java/cc/seeed/iot/webapi/model/OtaStatusResponse.java b/android/app/src/main/java/cc/seeed/iot/webapi/model/OtaStatusResponse.java index dcfd048..8a62a34 100755 --- a/android/app/src/main/java/cc/seeed/iot/webapi/model/OtaStatusResponse.java +++ b/android/app/src/main/java/cc/seeed/iot/webapi/model/OtaStatusResponse.java @@ -4,8 +4,6 @@ * Created by tenwong on 15/6/23. */ public class OtaStatusResponse { - public String status; - public String msg; public String ota_status; public String ota_msg; } diff --git a/android/app/src/main/java/cc/seeed/iot/webapi/model/ReadConfig.java b/android/app/src/main/java/cc/seeed/iot/webapi/model/ReadConfig.java new file mode 100755 index 0000000..d15568f --- /dev/null +++ b/android/app/src/main/java/cc/seeed/iot/webapi/model/ReadConfig.java @@ -0,0 +1,12 @@ +package cc.seeed.iot.webapi.model; + +import java.util.List; + +/** + * Created by tenwong on 15/6/25. + */ +public class ReadConfig { + public List Raw; + public List> Returns; + public List> Arguments; +} diff --git a/android/app/src/main/java/cc/seeed/iot/webapi/model/CommonResponse.java b/android/app/src/main/java/cc/seeed/iot/webapi/model/StatusResponse.java similarity index 64% rename from android/app/src/main/java/cc/seeed/iot/webapi/model/CommonResponse.java rename to android/app/src/main/java/cc/seeed/iot/webapi/model/StatusResponse.java index 17e1bf6..87eac77 100755 --- a/android/app/src/main/java/cc/seeed/iot/webapi/model/CommonResponse.java +++ b/android/app/src/main/java/cc/seeed/iot/webapi/model/StatusResponse.java @@ -3,7 +3,7 @@ /** * Created by tenwong on 15/6/23. */ -public class CommonResponse { - public String status; +public class StatusResponse { public String msg; + public String result; } diff --git a/android/app/src/main/java/cc/seeed/iot/webapi/model/SuccessResponse.java b/android/app/src/main/java/cc/seeed/iot/webapi/model/SuccessResponse.java new file mode 100755 index 0000000..823f6f4 --- /dev/null +++ b/android/app/src/main/java/cc/seeed/iot/webapi/model/SuccessResponse.java @@ -0,0 +1,8 @@ +package cc.seeed.iot.webapi.model; + +/** + * Created by tenwong on 15/6/23. + */ +public class SuccessResponse { + public String result; +} diff --git a/android/app/src/main/java/cc/seeed/iot/webapi/model/UserResponse.java b/android/app/src/main/java/cc/seeed/iot/webapi/model/UserResponse.java index 917b4e4..65c1d5c 100755 --- a/android/app/src/main/java/cc/seeed/iot/webapi/model/UserResponse.java +++ b/android/app/src/main/java/cc/seeed/iot/webapi/model/UserResponse.java @@ -4,8 +4,5 @@ * Created by tenwong on 15/6/23. */ public class UserResponse { - public String status; - public String msg; public String token; - public String user_id; } diff --git a/android/app/src/main/java/cc/seeed/iot/webapi/model/WellKnownResponse.java b/android/app/src/main/java/cc/seeed/iot/webapi/model/WellKnownResponse.java index 1270819..2d386d2 100755 --- a/android/app/src/main/java/cc/seeed/iot/webapi/model/WellKnownResponse.java +++ b/android/app/src/main/java/cc/seeed/iot/webapi/model/WellKnownResponse.java @@ -6,6 +6,5 @@ * Created by tenwong on 15/6/23. */ public class WellKnownResponse { - public String status; - public List msg; + public List well_known; } diff --git a/android/app/src/main/java/cc/seeed/iot/webapi/model/WriteConfig.java b/android/app/src/main/java/cc/seeed/iot/webapi/model/WriteConfig.java new file mode 100755 index 0000000..3e93e21 --- /dev/null +++ b/android/app/src/main/java/cc/seeed/iot/webapi/model/WriteConfig.java @@ -0,0 +1,10 @@ +package cc.seeed.iot.webapi.model; + +import java.util.List; + +/** + * Created by tenwong on 15/6/25. + */ +public class WriteConfig { + public List> Arguments; +} diff --git a/android/app/wio_link_2.1.0.apk b/android/app/wio_link_2.1.0.apk new file mode 100644 index 0000000..69ed67a Binary files /dev/null and b/android/app/wio_link_2.1.0.apk differ diff --git a/android/app/wio_link_2.1.1.apk b/android/app/wio_link_2.1.1.apk new file mode 100644 index 0000000..5501a94 Binary files /dev/null and b/android/app/wio_link_2.1.1.apk differ