From 8004525281f0776257140633fed9a0c9b34b7043 Mon Sep 17 00:00:00 2001 From: JianYe Date: Sat, 15 Jun 2019 10:54:04 +0800 Subject: [PATCH 1/6] =?UTF-8?q?=E5=90=8C=E6=AD=A5=E5=AE=98=E6=96=B9?= =?UTF-8?q?=E6=9C=80=E6=96=B00.3.7.1=E4=BB=A3=E7=A0=81=20=E4=BF=AE?= =?UTF-8?q?=E6=94=B9ios=E7=AB=AF=E6=BA=90=E7=A0=81=20=E4=BF=AE=E5=A4=8Dbug?= =?UTF-8?q?=20=E4=BB=A5=E5=8F=8A=E4=BF=9D=E6=8C=81=E4=B8=8E=E5=AE=89?= =?UTF-8?q?=E5=8D=93=E7=AB=AF=E4=B8=80=E8=87=B4=E7=9A=84=E5=A4=84=E7=90=86?= =?UTF-8?q?=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- android/build.gradle | 0 android/react-native-smartconfig-2.iml | 140 ++++ android/src/main/AndroidManifest.xml | 0 .../iot/esptouch/EsptouchResult.java | 84 +-- .../espressif/iot/esptouch/EsptouchTask.java | 167 +++-- .../iot/esptouch/IEsptouchListener.java | 15 +- .../iot/esptouch/IEsptouchResult.java | 50 +- .../espressif/iot/esptouch/IEsptouchTask.java | 104 +-- .../iot/esptouch/protocol/DataCode.java | 120 ++-- .../iot/esptouch/protocol/DatumCode.java | 273 ++++---- .../esptouch/protocol/EsptouchGenerator.java | 97 ++- .../iot/esptouch/protocol/GuideCode.java | 56 +- .../iot/esptouch/protocol/TouchData.java | 22 + .../esptouch/task/EsptouchTaskParameter.java | 313 ++++----- .../iot/esptouch/task/ICodeData.java | 27 +- .../iot/esptouch/task/IEsptouchGenerator.java | 24 +- .../esptouch/task/IEsptouchTaskParameter.java | 277 ++++---- .../iot/esptouch/task/__EsptouchTask.java | 631 +++++++++--------- .../iot/esptouch/task/__IEsptouchTask.java | 83 ++- .../iot/esptouch/udp/UDPSocketClient.java | 232 +++---- .../iot/esptouch/udp/UDPSocketServer.java | 257 ++++--- .../espressif/iot/esptouch/util/ByteUtil.java | 556 ++++++++------- .../com/espressif/iot/esptouch/util/CRC8.java | 114 ++-- .../espressif/iot/esptouch/util/EspAES.java | 104 +++ .../iot/esptouch/util/EspNetUtil.java | 96 --- .../iot/esptouch/util/TouchNetUtil.java | 123 ++++ .../RCTSmartconfig/RCTSmartconfigModule.java | 43 +- .../RCTSmartconfig/RCTSmartconfigPackage.java | 0 ios/RCTSmartconfig/ESPAES.h | 19 + ios/RCTSmartconfig/ESPAES.m | 66 ++ ios/RCTSmartconfig/ESPAppDelegate.m | 13 +- ios/RCTSmartconfig/ESPDatumCode.h | 2 +- ios/RCTSmartconfig/ESPDatumCode.m | 38 +- ios/RCTSmartconfig/ESPTouchGenerator.h | 2 +- ios/RCTSmartconfig/ESPTouchGenerator.m | 2 +- ios/RCTSmartconfig/ESPTouchTask.h | 12 +- ios/RCTSmartconfig/ESPTouchTask.m | 59 +- ios/RCTSmartconfig/ESPTouchTaskParameter.h | 5 + ios/RCTSmartconfig/ESPTouchTaskParameter.m | 17 +- ios/RCTSmartconfig/ESPViewController.h | 5 +- ios/RCTSmartconfig/ESPViewController.m | 300 +++++++++ ios/RCTSmartconfig/EspTouchDemo-Info.plist | 8 +- ios/RCTSmartconfig/IPAddress.c | 216 ------ ios/RCTSmartconfig/IPAddress.h | 26 - .../RCTSmartconfig.xcodeproj/project.pbxproj | 98 ++- ios/RCTSmartconfig/Smartconfig.m | 53 +- 46 files changed, 2757 insertions(+), 2192 deletions(-) mode change 100644 => 100755 android/build.gradle create mode 100755 android/react-native-smartconfig-2.iml mode change 100644 => 100755 android/src/main/AndroidManifest.xml mode change 100644 => 100755 android/src/main/java/com/espressif/iot/esptouch/EsptouchResult.java mode change 100644 => 100755 android/src/main/java/com/espressif/iot/esptouch/EsptouchTask.java mode change 100644 => 100755 android/src/main/java/com/espressif/iot/esptouch/IEsptouchListener.java mode change 100644 => 100755 android/src/main/java/com/espressif/iot/esptouch/IEsptouchResult.java mode change 100644 => 100755 android/src/main/java/com/espressif/iot/esptouch/IEsptouchTask.java mode change 100644 => 100755 android/src/main/java/com/espressif/iot/esptouch/protocol/DataCode.java mode change 100644 => 100755 android/src/main/java/com/espressif/iot/esptouch/protocol/DatumCode.java mode change 100644 => 100755 android/src/main/java/com/espressif/iot/esptouch/protocol/EsptouchGenerator.java mode change 100644 => 100755 android/src/main/java/com/espressif/iot/esptouch/protocol/GuideCode.java create mode 100755 android/src/main/java/com/espressif/iot/esptouch/protocol/TouchData.java mode change 100644 => 100755 android/src/main/java/com/espressif/iot/esptouch/task/EsptouchTaskParameter.java mode change 100644 => 100755 android/src/main/java/com/espressif/iot/esptouch/task/ICodeData.java mode change 100644 => 100755 android/src/main/java/com/espressif/iot/esptouch/task/IEsptouchGenerator.java mode change 100644 => 100755 android/src/main/java/com/espressif/iot/esptouch/task/IEsptouchTaskParameter.java mode change 100644 => 100755 android/src/main/java/com/espressif/iot/esptouch/task/__EsptouchTask.java mode change 100644 => 100755 android/src/main/java/com/espressif/iot/esptouch/task/__IEsptouchTask.java mode change 100644 => 100755 android/src/main/java/com/espressif/iot/esptouch/udp/UDPSocketClient.java mode change 100644 => 100755 android/src/main/java/com/espressif/iot/esptouch/udp/UDPSocketServer.java mode change 100644 => 100755 android/src/main/java/com/espressif/iot/esptouch/util/ByteUtil.java mode change 100644 => 100755 android/src/main/java/com/espressif/iot/esptouch/util/CRC8.java create mode 100755 android/src/main/java/com/espressif/iot/esptouch/util/EspAES.java delete mode 100644 android/src/main/java/com/espressif/iot/esptouch/util/EspNetUtil.java create mode 100755 android/src/main/java/com/espressif/iot/esptouch/util/TouchNetUtil.java mode change 100644 => 100755 android/src/main/java/com/tuanpm/RCTSmartconfig/RCTSmartconfigModule.java mode change 100644 => 100755 android/src/main/java/com/tuanpm/RCTSmartconfig/RCTSmartconfigPackage.java create mode 100755 ios/RCTSmartconfig/ESPAES.h create mode 100755 ios/RCTSmartconfig/ESPAES.m create mode 100755 ios/RCTSmartconfig/ESPViewController.m delete mode 100644 ios/RCTSmartconfig/IPAddress.c delete mode 100644 ios/RCTSmartconfig/IPAddress.h diff --git a/android/build.gradle b/android/build.gradle old mode 100644 new mode 100755 diff --git a/android/react-native-smartconfig-2.iml b/android/react-native-smartconfig-2.iml new file mode 100755 index 0000000..511de04 --- /dev/null +++ b/android/react-native-smartconfig-2.iml @@ -0,0 +1,140 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/android/src/main/AndroidManifest.xml b/android/src/main/AndroidManifest.xml old mode 100644 new mode 100755 diff --git a/android/src/main/java/com/espressif/iot/esptouch/EsptouchResult.java b/android/src/main/java/com/espressif/iot/esptouch/EsptouchResult.java old mode 100644 new mode 100755 index 1e912d9..8d6af6b --- a/android/src/main/java/com/espressif/iot/esptouch/EsptouchResult.java +++ b/android/src/main/java/com/espressif/iot/esptouch/EsptouchResult.java @@ -5,47 +5,47 @@ 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; - } + 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/src/main/java/com/espressif/iot/esptouch/EsptouchTask.java b/android/src/main/java/com/espressif/iot/esptouch/EsptouchTask.java old mode 100644 new mode 100755 index 3a798d9..7cedc02 --- a/android/src/main/java/com/espressif/iot/esptouch/EsptouchTask.java +++ b/android/src/main/java/com/espressif/iot/esptouch/EsptouchTask.java @@ -1,89 +1,112 @@ package com.espressif.iot.esptouch; -import java.util.List; - import android.content.Context; +import android.text.TextUtils; +import com.espressif.iot.esptouch.protocol.TouchData; import com.espressif.iot.esptouch.task.EsptouchTaskParameter; -import com.espressif.iot.esptouch.task.IEsptouchTaskParameter; import com.espressif.iot.esptouch.task.__EsptouchTask; +import com.espressif.iot.esptouch.util.EspAES; +import com.espressif.iot.esptouch.util.TouchNetUtil; + +import java.util.List; public class EsptouchTask implements IEsptouchTask { + private __EsptouchTask _mEsptouchTask; + private EsptouchTaskParameter _mParameter; + + /** + * Constructor of EsptouchTask + * + * @param apSsid the Ap's ssid + * @param apBssid the Ap's bssid + * @param apPassword the Ap's password + * @param context the {@link Context} of the Application + */ + public EsptouchTask(String apSsid, String apBssid, String apPassword, Context context) { + this(apSsid, apBssid, apPassword, null, context); + } + + /** + * Constructor of EsptouchTask + * + * @param apSsid the Ap's ssid + * @param apBssid the Ap's bssid + * @param apPassword the Ap's password + * @param context the {@link Context} of the Application + */ + public EsptouchTask(byte[] apSsid, byte[] apBssid, byte[] apPassword, Context context) { + this(apSsid, apBssid, apPassword, null, context); + } + + private EsptouchTask(String apSsid, String apBssid, String apPassword, EspAES espAES, Context context) { + if (TextUtils.isEmpty(apSsid)) { + throw new NullPointerException("SSID can't be empty"); + } + if (TextUtils.isEmpty(apBssid)) { + throw new NullPointerException("BSSID can't be empty"); + } + if (apPassword == null) { + apPassword = ""; + } + TouchData ssid = new TouchData(apSsid); + TouchData bssid = new TouchData(TouchNetUtil.parseBssid2bytes(apBssid)); + TouchData password = new TouchData(apPassword); + init(context, ssid, bssid, password, espAES); + } - public __EsptouchTask _mEsptouchTask; - private IEsptouchTaskParameter _mParameter; + private EsptouchTask(byte[] apSsid, byte[] apBssid, byte[] apPassword, EspAES espAES, Context context) { + if (apSsid == null || apSsid.length == 0) { + throw new NullPointerException("SSID can't be empty"); + } + if (apBssid == null || apBssid.length == 0) { + throw new NullPointerException("BSSID can't be empty"); + } + if (apPassword == null) { + apPassword = new byte[0]; + } + TouchData ssid = new TouchData(apSsid); + TouchData bssid = new TouchData(apBssid); + TouchData password = new TouchData(apPassword); + init(context, ssid, bssid, password, espAES); + } - /** - * 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); - } + private void init(Context context, TouchData ssid, TouchData bssid, TouchData password, EspAES aes) { + _mParameter = new EsptouchTaskParameter(); + _mEsptouchTask = new __EsptouchTask(context, ssid, bssid, password, aes, _mParameter, true); + } - /** - * 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 >= 15000+6000) 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 void interrupt() { - _mEsptouchTask.interrupt(); - } + @Override + public IEsptouchResult executeForResult() throws RuntimeException { + return _mEsptouchTask.executeForResult(); + } - @Override - public IEsptouchResult executeForResult() throws RuntimeException { - return _mEsptouchTask.executeForResult(); - } + @Override + public boolean isCancelled() { + return _mEsptouchTask.isCancelled(); + } - @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); + } - @Override - public List executeForResults(int expectTaskResultCount) - throws RuntimeException { - if (expectTaskResultCount <= 0) { - expectTaskResultCount = Integer.MAX_VALUE; - } - return _mEsptouchTask.executeForResults(expectTaskResultCount); - } + @Override + public void setEsptouchListener(IEsptouchListener esptouchListener) { + _mEsptouchTask.setEsptouchListener(esptouchListener); + } - @Override - public void setEsptouchListener(IEsptouchListener esptouchListener) { - _mEsptouchTask.setEsptouchListener(esptouchListener); - } + @Override + public void setPackageBroadcast(boolean broadcast) { + _mParameter.setBroadcast(broadcast); + } } diff --git a/android/src/main/java/com/espressif/iot/esptouch/IEsptouchListener.java b/android/src/main/java/com/espressif/iot/esptouch/IEsptouchListener.java old mode 100644 new mode 100755 index 6312549..4c9d992 --- a/android/src/main/java/com/espressif/iot/esptouch/IEsptouchListener.java +++ b/android/src/main/java/com/espressif/iot/esptouch/IEsptouchListener.java @@ -1,12 +1,11 @@ package com.espressif.iot.esptouch; public interface IEsptouchListener { - /** - * when new esptouch result is added, the listener will call - * onEsptouchResultAdded callback - * - * @param result - * the Esptouch result - */ - void onEsptouchResultAdded(IEsptouchResult result); + /** + * when new esptouch result is added, the listener will call + * onEsptouchResultAdded callback + * + * @param result the Esptouch result + */ + void onEsptouchResultAdded(IEsptouchResult result); } diff --git a/android/src/main/java/com/espressif/iot/esptouch/IEsptouchResult.java b/android/src/main/java/com/espressif/iot/esptouch/IEsptouchResult.java old mode 100644 new mode 100755 index 6483e97..0aad878 --- a/android/src/main/java/com/espressif/iot/esptouch/IEsptouchResult.java +++ b/android/src/main/java/com/espressif/iot/esptouch/IEsptouchResult.java @@ -3,32 +3,32 @@ 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 executed suc + * + * @return whether the esptouch task is executed suc + */ + boolean isSuc(); - /** - * check whether the esptouch task is cancelled by user - * - * @return whether the esptouch task is cancelled by user - */ - boolean isCancelled(); + /** + * get the device's bssid + * + * @return the device's bssid + */ + String getBssid(); - /** - * get the ip address of the device - * - * @return the ip device of the device - */ - InetAddress getInetAddress(); + /** + * 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/src/main/java/com/espressif/iot/esptouch/IEsptouchTask.java b/android/src/main/java/com/espressif/iot/esptouch/IEsptouchTask.java old mode 100644 new mode 100755 index dfa1ebe..f5a24bf --- a/android/src/main/java/com/espressif/iot/esptouch/IEsptouchTask.java +++ b/android/src/main/java/com/espressif/iot/esptouch/IEsptouchTask.java @@ -3,53 +3,61 @@ import java.util.List; public interface IEsptouchTask { + String ESPTOUCH_VERSION = "v0.3.7.1"; - /** - * set the esptouch listener, when one device is connected to the Ap, it will be called back - * @param esptouchListener when one device is connected to the Ap, it will be called back - */ - void setEsptouchListener(IEsptouchListener esptouchListener); - - /** - * 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.4 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.4 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(); + /** + * set the esptouch listener, when one device is connected to the Ap, it will be called back + * + * @param esptouchListener when one device is connected to the Ap, it will be called back + */ + void setEsptouchListener(IEsptouchListener esptouchListener); + + /** + * 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.4 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.4 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(); + + /** + * Set broadcast or multicast when post config info + * + * @param broadcast true is broadcast, false is multicast + */ + void setPackageBroadcast(boolean broadcast); } diff --git a/android/src/main/java/com/espressif/iot/esptouch/protocol/DataCode.java b/android/src/main/java/com/espressif/iot/esptouch/protocol/DataCode.java old mode 100644 new mode 100755 index 8568a6d..ada4cce --- a/android/src/main/java/com/espressif/iot/esptouch/protocol/DataCode.java +++ b/android/src/main/java/com/espressif/iot/esptouch/protocol/DataCode.java @@ -6,82 +6,82 @@ /** * one data format:(data code should have 2 to 65 data) - * - * control byte high 4 bits low 4 bits + *

+ * 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; +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 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(); - } + 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()"); - } + @Override + public char[] getU8s() { + throw new RuntimeException("DataCode don't support getU8s()"); + } } diff --git a/android/src/main/java/com/espressif/iot/esptouch/protocol/DatumCode.java b/android/src/main/java/com/espressif/iot/esptouch/protocol/DatumCode.java old mode 100644 new mode 100755 index 64ae784..978d54b --- a/android/src/main/java/com/espressif/iot/esptouch/protocol/DatumCode.java +++ b/android/src/main/java/com/espressif/iot/esptouch/protocol/DatumCode.java @@ -1,145 +1,144 @@ package com.espressif.iot.esptouch.protocol; -import java.net.InetAddress; - import com.espressif.iot.esptouch.task.ICodeData; import com.espressif.iot.esptouch.util.ByteUtil; import com.espressif.iot.esptouch.util.CRC8; -import com.espressif.iot.esptouch.util.EspNetUtil; + +import java.net.InetAddress; +import java.util.LinkedList; 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 isSsidHiden) { - // 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 = isSsidHiden ? (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 (isSsidHiden) { - 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; - } + + // 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 LinkedList 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 isSsidHiden whether the Ap's ssid is hidden + */ + public DatumCode(byte[] apSsid, byte[] apBssid, byte[] apPassword, + InetAddress ipAddress, boolean isSsidHiden) { + // 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) apPassword.length; + CRC8 crc = new CRC8(); + crc.update(apSsid); + char apSsidCrc = (char) crc.getValue(); + + crc.reset(); + crc.update(apBssid); + char apBssidCrc = (char) crc.getValue(); + + char apSsidLen = (char) apSsid.length; + + byte[] ipBytes = ipAddress.getAddress(); + int ipLen = ipBytes.length; + + char _totalLen = (char) (EXTRA_HEAD_LEN + ipLen + apPwdLen + apSsidLen); + char totalLen = isSsidHiden ? (char) (EXTRA_HEAD_LEN + ipLen + apPwdLen + apSsidLen) + : (char) (EXTRA_HEAD_LEN + ipLen + apPwdLen); + + // build data codes + mDataCodes = new LinkedList<>(); + mDataCodes.add(new DataCode(_totalLen, 0)); + totalXor ^= _totalLen; + mDataCodes.add(new DataCode(apPwdLen, 1)); + totalXor ^= apPwdLen; + mDataCodes.add(new DataCode(apSsidCrc, 2)); + totalXor ^= apSsidCrc; + mDataCodes.add(new DataCode(apBssidCrc, 3)); + totalXor ^= apBssidCrc; + // ESPDataCode 4 is null + for (int i = 0; i < ipLen; ++i) { + char c = ByteUtil.convertByte2Uint8(ipBytes[i]); + totalXor ^= c; + mDataCodes.add(new DataCode(c, i + EXTRA_HEAD_LEN)); + } + + for (int i = 0; i < apPassword.length; i++) { + char c = ByteUtil.convertByte2Uint8(apPassword[i]); + totalXor ^= c; + mDataCodes.add(new DataCode(c, i + EXTRA_HEAD_LEN + ipLen)); + } + + // totalXor will xor apSsidChars no matter whether the ssid is hidden + for (int i = 0; i < apSsid.length; i++) { + char c = ByteUtil.convertByte2Uint8(apSsid[i]); + totalXor ^= c; + if (isSsidHiden) { + mDataCodes.add(new DataCode(c, i + EXTRA_HEAD_LEN + ipLen + apPwdLen)); + } + } + + // add total xor last + mDataCodes.add(4, new DataCode(totalXor, 4)); + + // add bssid + int bssidInsertIndex = EXTRA_HEAD_LEN; + for (int i = 0; i < apBssid.length; i++) { + int index = totalLen + i; + char c = ByteUtil.convertByte2Uint8(apBssid[i]); + DataCode dc = new DataCode(c, index); + if (bssidInsertIndex >= mDataCodes.size()) { + mDataCodes.add(dc); + } else { + mDataCodes.add(bssidInsertIndex, dc); + } + bssidInsertIndex += 4; + } + } + + @Override + public byte[] getBytes() { + byte[] datumCode = new byte[mDataCodes.size() * DataCode.DATA_CODE_LEN]; + int index = 0; + for (DataCode dc : mDataCodes) { + for (byte b : dc.getBytes()) { + datumCode[index++] = b; + } + } + return datumCode; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + byte[] dataBytes = getBytes(); + for (byte dataByte : dataBytes) { + String hexString = ByteUtil.convertByte2HexString(dataByte); + 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/src/main/java/com/espressif/iot/esptouch/protocol/EsptouchGenerator.java b/android/src/main/java/com/espressif/iot/esptouch/protocol/EsptouchGenerator.java old mode 100644 new mode 100755 index 7c96f40..d9e4995 --- a/android/src/main/java/com/espressif/iot/esptouch/protocol/EsptouchGenerator.java +++ b/android/src/main/java/com/espressif/iot/esptouch/protocol/EsptouchGenerator.java @@ -1,60 +1,55 @@ package com.espressif.iot.esptouch.protocol; -import java.net.InetAddress; - import com.espressif.iot.esptouch.task.IEsptouchGenerator; import com.espressif.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; - } + 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 isSsidHiden whether the Ap's ssid is hidden + */ + public EsptouchGenerator(byte[] apSsid, byte[] apBssid, byte[] 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/src/main/java/com/espressif/iot/esptouch/protocol/GuideCode.java b/android/src/main/java/com/espressif/iot/esptouch/protocol/GuideCode.java old mode 100644 new mode 100755 index d24383e..a49bea2 --- a/android/src/main/java/com/espressif/iot/esptouch/protocol/GuideCode.java +++ b/android/src/main/java/com/espressif/iot/esptouch/protocol/GuideCode.java @@ -5,35 +5,35 @@ public class GuideCode implements ICodeData { - public static final int GUIDE_CODE_LEN = 4; + public static final int GUIDE_CODE_LEN = 4; - @Override - public byte[] getBytes() { - throw new RuntimeException("DataCode don't support getBytes()"); - } + @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 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; - } + @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/src/main/java/com/espressif/iot/esptouch/protocol/TouchData.java b/android/src/main/java/com/espressif/iot/esptouch/protocol/TouchData.java new file mode 100755 index 0000000..f96afaf --- /dev/null +++ b/android/src/main/java/com/espressif/iot/esptouch/protocol/TouchData.java @@ -0,0 +1,22 @@ +package com.espressif.iot.esptouch.protocol; + +import com.espressif.iot.esptouch.util.ByteUtil; + +public class TouchData { + private final byte[] mData; + + public TouchData(String string) { + mData = ByteUtil.getBytesByString(string); + } + + public TouchData(byte[] data) { + if (data == null) { + throw new NullPointerException("data can't be null"); + } + mData = data; + } + + public byte[] getData() { + return mData; + } +} diff --git a/android/src/main/java/com/espressif/iot/esptouch/task/EsptouchTaskParameter.java b/android/src/main/java/com/espressif/iot/esptouch/task/EsptouchTaskParameter.java old mode 100644 new mode 100755 index eaf10b5..129f8aa --- a/android/src/main/java/com/espressif/iot/esptouch/task/EsptouchTaskParameter.java +++ b/android/src/main/java/com/espressif/iot/esptouch/task/EsptouchTaskParameter.java @@ -1,156 +1,167 @@ package com.espressif.iot.esptouch.task; -public class EsptouchTaskParameter implements IEsptouchTaskParameter { +import com.espressif.iot.esptouch.EsptouchTask; - 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 int mTargetPort; - private int mWaitUdpReceivingMilliseond; - private int mWaitUdpSendingMillisecond; - private int mThresholdSucBroadcastCount; - private int mExpectTaskResultCount; - private static int _datagramCount = 0; - - public EsptouchTaskParameter() { - mIntervalGuideCodeMillisecond = 10; - mIntervalDataCodeMillisecond = 10; - mTimeoutGuideCodeMillisecond = 2000; - mTimeoutDataCodeMillisecond = 4000; - mTotalRepeatTime = 1; - mEsptouchResultOneLen = 1; - mEsptouchResultMacLen = 6; - mEsptouchResultIpLen = 4; - mEsptouchResultTotalLen = 1 + 6 + 4; - mPortListening = 18266; - mTargetPort = 7001; - mWaitUdpReceivingMilliseond = 15000; - mWaitUdpSendingMillisecond = 45000; - mThresholdSucBroadcastCount = 1; - mExpectTaskResultCount = 1; - } - - // the range of the result should be 1-100 - private static int __getNextDatagramCount() { - return 1 + (_datagramCount++) % 100; - } - - @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; - } - - // target hostname is : 234.1.1.1, 234.2.2.2, 234.3.3.3 to 234.100.100.100 - @Override - public String getTargetHostname() { - int count = __getNextDatagramCount(); - return "234." + count + "." + count + "." + count; - } - - @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; - } +public class EsptouchTaskParameter implements IEsptouchTaskParameter { + private static int _datagramCount = 0; + 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 int mTargetPort; + private int mWaitUdpReceivingMilliseond; + private int mWaitUdpSendingMillisecond; + private int mThresholdSucBroadcastCount; + private int mExpectTaskResultCount; + private boolean mBroadcast = true; + + public EsptouchTaskParameter() { + mIntervalGuideCodeMillisecond = 8; + mIntervalDataCodeMillisecond = 8; + mTimeoutGuideCodeMillisecond = 2000; + mTimeoutDataCodeMillisecond = 4000; + mTotalRepeatTime = 1; + mEsptouchResultOneLen = 1; + mEsptouchResultMacLen = 6; + mEsptouchResultIpLen = 4; + mEsptouchResultTotalLen = 1 + 6 + 4; + mPortListening = 18266; + mTargetPort = 7001; + mWaitUdpReceivingMilliseond = 15000; + mWaitUdpSendingMillisecond = 45000; + mThresholdSucBroadcastCount = 1; + mExpectTaskResultCount = 1; + } + + // the range of the result should be 1-100 + private static int __getNextDatagramCount() { + return 1 + (_datagramCount++) % 100; + } + + @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; + } + + // target hostname is : 234.1.1.1, 234.2.2.2, 234.3.3.3 to 234.100.100.100 + @Override + public String getTargetHostname() { + if (mBroadcast) { + return "255.255.255.255"; + } else { + int count = __getNextDatagramCount(); + return "234." + count + "." + count + "." + count; + } + } + + @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 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 getThresholdSucBroadcastCount() { + return mThresholdSucBroadcastCount; + } + + @Override + public int getExpectTaskResultCount() { + return this.mExpectTaskResultCount; + } + + @Override + public void setExpectTaskResultCount(int expectTaskResultCount) { + this.mExpectTaskResultCount = expectTaskResultCount; + } + + @Override + public void setBroadcast(boolean broadcast) { + mBroadcast = broadcast; + } } diff --git a/android/src/main/java/com/espressif/iot/esptouch/task/ICodeData.java b/android/src/main/java/com/espressif/iot/esptouch/task/ICodeData.java old mode 100644 new mode 100755 index 268d081..64e9c9b --- a/android/src/main/java/com/espressif/iot/esptouch/task/ICodeData.java +++ b/android/src/main/java/com/espressif/iot/esptouch/task/ICodeData.java @@ -2,22 +2,21 @@ /** * the class used to represent some code to be transformed by UDP socket should implement the interface - * @author afunx * + * @author afunx */ public interface ICodeData { - /** - * Get the byte[] to be transformed. - * - * - * @return the byte[] to be transfromed - */ - byte[] getBytes(); + /** + * 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(); + /** + * Get the char[](u8[]) to be transfromed. + * + * @return the char[](u8) to be transformed + */ + char[] getU8s(); } diff --git a/android/src/main/java/com/espressif/iot/esptouch/task/IEsptouchGenerator.java b/android/src/main/java/com/espressif/iot/esptouch/task/IEsptouchGenerator.java old mode 100644 new mode 100755 index 4fa07a3..07c8981 --- a/android/src/main/java/com/espressif/iot/esptouch/task/IEsptouchGenerator.java +++ b/android/src/main/java/com/espressif/iot/esptouch/task/IEsptouchGenerator.java @@ -1,17 +1,17 @@ package com.espressif.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 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(); + /** + * Get data code by the format of byte[][] + * + * @return data code by the format of byte[][] + */ + byte[][] getDCBytes2(); } diff --git a/android/src/main/java/com/espressif/iot/esptouch/task/IEsptouchTaskParameter.java b/android/src/main/java/com/espressif/iot/esptouch/task/IEsptouchTaskParameter.java old mode 100644 new mode 100755 index b437f5a..f40e953 --- a/android/src/main/java/com/espressif/iot/esptouch/task/IEsptouchTaskParameter.java +++ b/android/src/main/java/com/espressif/iot/esptouch/task/IEsptouchTaskParameter.java @@ -1,129 +1,156 @@ package com.espressif.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); + + /** + * 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(); + + /** + * 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 threshold for how many correct broadcast should be received + * + * @return the threshold for how many correct broadcast should be received + */ + int getThresholdSucBroadcastCount(); + + /** + * 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); + + /** + * Set broadcast or multicast + * + * @param broadcast true is broadcast, false is multicast + */ + void setBroadcast(boolean broadcast); } diff --git a/android/src/main/java/com/espressif/iot/esptouch/task/__EsptouchTask.java b/android/src/main/java/com/espressif/iot/esptouch/task/__EsptouchTask.java old mode 100644 new mode 100755 index 9cd5264..b8a50ba --- a/android/src/main/java/com/espressif/iot/esptouch/task/__EsptouchTask.java +++ b/android/src/main/java/com/espressif/iot/esptouch/task/__EsptouchTask.java @@ -1,349 +1,356 @@ package com.espressif.iot.esptouch.task; -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; +import android.content.Context; +import android.os.Looper; +import android.util.Log; import com.espressif.iot.esptouch.EsptouchResult; import com.espressif.iot.esptouch.IEsptouchListener; import com.espressif.iot.esptouch.IEsptouchResult; +import com.espressif.iot.esptouch.IEsptouchTask; import com.espressif.iot.esptouch.protocol.EsptouchGenerator; +import com.espressif.iot.esptouch.protocol.TouchData; import com.espressif.iot.esptouch.udp.UDPSocketClient; import com.espressif.iot.esptouch.udp.UDPSocketServer; import com.espressif.iot.esptouch.util.ByteUtil; -import com.espressif.iot.esptouch.util.EspNetUtil; +import com.espressif.iot.esptouch.util.EspAES; +import com.espressif.iot.esptouch.util.TouchNetUtil; -import android.content.Context; -import android.os.Looper; -import android.text.TextUtils; -import android.util.Log; +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"; - /** - * one indivisible data contain 3 9bits info - */ - private static final int ONE_DATA_LEN = 3; + private final UDPSocketClient mSocketClient; + private final UDPSocketServer mSocketServer; + private final byte[] mApSsid; + private final byte[] mApPassword; + private final byte[] mApBssid; + private final boolean mIsSsidHidden; + private final Context mContext; + private volatile List mEsptouchResultList; + private volatile boolean mIsSuc = false; + private volatile boolean mIsInterrupt = false; + private volatile boolean mIsExecuted = false; + private AtomicBoolean mIsCancelled; + private IEsptouchTaskParameter mParameter; + private volatile Map mBssidTaskSucCountMap; + private IEsptouchListener mEsptouchListener; + private Thread mTask; - private static final String TAG = "EsptouchTask"; + public __EsptouchTask(Context context, TouchData apSsid, TouchData apBssid, TouchData apPassword, EspAES espAES, + IEsptouchTaskParameter parameter, boolean isSsidHidden) { + Log.i(TAG, "Welcome Esptouch " + IEsptouchTask.ESPTOUCH_VERSION); + mContext = context; + if (espAES == null) { + mApSsid = apSsid.getData(); + mApPassword = apPassword.getData(); + } else { + mApSsid = espAES.encrypt(apSsid.getData()); + mApPassword = espAES.encrypt(apPassword.getData()); + } + mApBssid = apBssid.getData(); + 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 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; - private IEsptouchListener mEsptouchListener; + 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 (__IEsptouchTask.DEBUG) { + Log.d(TAG, "__putEsptouchResult(): count = " + count); + } + mBssidTaskSucCountMap.put(bssid, count); + isTaskSucCountEnough = count >= mParameter + .getThresholdSucBroadcastCount(); + if (!isTaskSucCountEnough) { + if (__IEsptouchTask.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 (__IEsptouchTask.DEBUG) { + Log.d(TAG, "__putEsptouchResult(): put one more result " + + "bssid = " + bssid + " , address = " + inetAddress); + } + final IEsptouchResult esptouchResult = new EsptouchResult(isSuc, + bssid, inetAddress); + mEsptouchResultList.add(esptouchResult); + if (mEsptouchListener != null) { + mEsptouchListener.onEsptouchResultAdded(esptouchResult); + } + } + } + } - 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 List __getEsptouchResultList() { + synchronized (mEsptouchResultList) { + if (mEsptouchResultList.isEmpty()) { + EsptouchResult esptouchResultFail = new EsptouchResult(false, + null, null); + esptouchResultFail.setIsCancelled(mIsCancelled.get()); + mEsptouchResultList.add(esptouchResultFail); + } - 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 (__IEsptouchTask.DEBUG) { - Log.d(TAG, "__putEsptouchResult(): count = " + count); - } - mBssidTaskSucCountMap.put(bssid, count); - isTaskSucCountEnough = count >= mParameter - .getThresholdSucBroadcastCount(); - if (!isTaskSucCountEnough) { - if (__IEsptouchTask.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 (__IEsptouchTask.DEBUG) { - Log.d(TAG, "__putEsptouchResult(): put one more result"); - } - final IEsptouchResult esptouchResult = new EsptouchResult(isSuc, - bssid, inetAddress); - mEsptouchResultList.add(esptouchResult); - if (mEsptouchListener != null) { - mEsptouchListener.onEsptouchResultAdded(esptouchResult); - } - } - } - } + return mEsptouchResultList; + } + } - 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 + if (mTask != null) { + mTask.interrupt(); + mTask = null; + } + } + } - 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 (__IEsptouchTask.DEBUG) { + Log.d(TAG, "interrupt()"); + } + mIsCancelled.set(true); + __interrupt(); + } - @Override - public void interrupt() { - if (__IEsptouchTask.DEBUG) { - Log.d(TAG, "interrupt()"); - } - mIsCancelled.set(true); - __interrupt(); - } + private void __listenAsyn(final int expectDataLen) { + mTask = new Thread() { + public void run() { + if (__IEsptouchTask.DEBUG) { + Log.d(TAG, "__listenAsyn() start"); + } + long startTimestamp = System.currentTimeMillis(); +// byte[] apSsidAndPassword = ByteUtil.getBytesByString(mApSsid +// + mApPassword); + byte expectOneByte = (byte) (mApSsid.length + mApPassword.length + 9); + if (__IEsptouchTask.DEBUG) { + Log.i(TAG, "expectOneByte: " + 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 (__IEsptouchTask.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 (__IEsptouchTask.DEBUG) { + Log.i(TAG, "esptouch timeout"); + } + break; + } else { + if (__IEsptouchTask.DEBUG) { + Log.i(TAG, "mSocketServer's new timeout is " + + timeout + " milliseconds"); + } + mSocketServer.setSoTimeout(timeout); + if (__IEsptouchTask.DEBUG) { + Log.i(TAG, "receive correct broadcast"); + } + if (receiveBytes != null) { + String bssid = ByteUtil.parseBssid( + receiveBytes, + mParameter.getEsptouchResultOneLen(), + mParameter.getEsptouchResultMacLen()); + InetAddress inetAddress = TouchNetUtil + .parseInetAddr( + receiveBytes, + mParameter + .getEsptouchResultOneLen() + + mParameter + .getEsptouchResultMacLen(), + mParameter + .getEsptouchResultIpLen()); + __putEsptouchResult(true, bssid, inetAddress); + } + } + } else { + if (__IEsptouchTask.DEBUG) { + Log.i(TAG, "receive rubbish message, just ignore"); + } + } + } + mIsSuc = mEsptouchResultList.size() >= mParameter + .getExpectTaskResultCount(); + __EsptouchTask.this.__interrupt(); + if (__IEsptouchTask.DEBUG) { + Log.d(TAG, "__listenAsyn() finish"); + } + } + }; + mTask.start(); + } - private void __listenAsyn(final int expectDataLen) { - new Thread() { - public void run() { - if (__IEsptouchTask.DEBUG) { - Log.d(TAG, "__listenAsyn() start"); - } - long startTimestamp = System.currentTimeMillis(); - byte[] apSsidAndPassword = ByteUtil.getBytesByString(mApSsid - + mApPassword); - byte expectOneByte = (byte) (apSsidAndPassword.length + 9); - if (__IEsptouchTask.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 (__IEsptouchTask.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 (__IEsptouchTask.DEBUG) { - Log.i(TAG, "esptouch timeout"); - } - break; - } else { - if (__IEsptouchTask.DEBUG) { - Log.i(TAG, "mSocketServer's new timeout is " - + timeout + " milliseconds"); - } - mSocketServer.setSoTimeout(timeout); - if (__IEsptouchTask.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 (__IEsptouchTask.DEBUG) { - Log.i(TAG, "receive rubbish message, just ignore"); - } - } - } - mIsSuc = mEsptouchResultList.size() >= mParameter - .getExpectTaskResultCount(); - __EsptouchTask.this.__interrupt(); - if (__IEsptouchTask.DEBUG) { - Log.d(TAG, "__listenAsyn() finish"); - } - } - }.start(); - } + private boolean __execute(IEsptouchGenerator generator) { - private boolean __execute(IEsptouchGenerator generator) { + long startTime = System.currentTimeMillis(); + long currentTime = startTime; + long lastTime = currentTime - mParameter.getTimeoutTotalCodeMillisecond(); - long startTime = System.currentTimeMillis(); - long currentTime = startTime; - long lastTime = currentTime - mParameter.getTimeoutTotalCodeMillisecond(); + byte[][] gcBytes2 = generator.getGCBytes2(); + byte[][] dcBytes2 = generator.getDCBytes2(); - byte[][] gcBytes2 = generator.getGCBytes2(); - byte[][] dcBytes2 = generator.getDCBytes2(); + int index = 0; + while (!mIsInterrupt) { + if (currentTime - lastTime >= mParameter.getTimeoutTotalCodeMillisecond()) { + if (__IEsptouchTask.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; + } + } - int index = 0; - while (!mIsInterrupt) { - if (currentTime - lastTime >= mParameter.getTimeoutTotalCodeMillisecond()) { - if (__IEsptouchTask.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; + } - 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; + } - 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 IEsptouchResult executeForResult() throws RuntimeException { - return executeForResults(1).get(0); - } + @Override + public boolean isCancelled() { + return this.mIsCancelled.get(); + } - @Override - public boolean isCancelled() { - return this.mIsCancelled.get(); - } + @Override + public List executeForResults(int expectTaskResultCount) + throws RuntimeException { + __checkTaskValid(); - @Override - public List executeForResults(int expectTaskResultCount) - throws RuntimeException { - __checkTaskValid(); + mParameter.setExpectTaskResultCount(expectTaskResultCount); - mParameter.setExpectTaskResultCount(expectTaskResultCount); + if (__IEsptouchTask.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 = TouchNetUtil.getLocalInetAddress(mContext); + if (__IEsptouchTask.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(); + } + } - if (__IEsptouchTask.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 (__IEsptouchTask.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(); - } - } + if (!mIsInterrupt) { + // 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(); + } - if (!mIsInterrupt) { - // 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(); - } + return __getEsptouchResultList(); + } - @Override - public void setEsptouchListener(IEsptouchListener esptouchListener) { - mEsptouchListener = esptouchListener; - } + @Override + public void setEsptouchListener(IEsptouchListener esptouchListener) { + mEsptouchListener = esptouchListener; + } } diff --git a/android/src/main/java/com/espressif/iot/esptouch/task/__IEsptouchTask.java b/android/src/main/java/com/espressif/iot/esptouch/task/__IEsptouchTask.java old mode 100644 new mode 100755 index 36b78c0..216e09b --- a/android/src/main/java/com/espressif/iot/esptouch/task/__IEsptouchTask.java +++ b/android/src/main/java/com/espressif/iot/esptouch/task/__IEsptouchTask.java @@ -1,56 +1,55 @@ package com.espressif.iot.esptouch.task; -import java.util.List; - import com.espressif.iot.esptouch.IEsptouchListener; import com.espressif.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 { - /** - * set the esptouch listener, when one device is connected to the Ap, it will be called back - * @param esptouchListener when one device is connected to the Ap, it will be called back - */ - void setEsptouchListener(IEsptouchListener esptouchListener); - - /** - * 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(); + /** + * Turn on or off the log. + */ + static final boolean DEBUG = true; + + /** + * set the esptouch listener, when one device is connected to the Ap, it will be called back + * + * @param esptouchListener when one device is connected to the Ap, it will be called back + */ + void setEsptouchListener(IEsptouchListener esptouchListener); + + /** + * 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; + + boolean isCancelled(); } diff --git a/android/src/main/java/com/espressif/iot/esptouch/udp/UDPSocketClient.java b/android/src/main/java/com/espressif/iot/esptouch/udp/UDPSocketClient.java old mode 100644 new mode 100755 index 517bcbc..7ca7880 --- a/android/src/main/java/com/espressif/iot/esptouch/udp/UDPSocketClient.java +++ b/android/src/main/java/com/espressif/iot/esptouch/udp/UDPSocketClient.java @@ -1,5 +1,9 @@ package com.espressif.iot.esptouch.udp; +import android.util.Log; + +import com.espressif.iot.esptouch.task.__IEsptouchTask; + import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; @@ -7,138 +11,120 @@ import java.net.SocketException; import java.net.UnknownHostException; -import com.espressif.iot.esptouch.task.__IEsptouchTask; - -import android.util.Log; - /** * 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; + 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.w(TAG, "SocketException"); + } + e.printStackTrace(); + } + } + + @Override + protected void finalize() throws Throwable { + close(); + super.finalize(); + } - 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(); - } - } + public void interrupt() { + if (__IEsptouchTask.DEBUG) { + Log.i(TAG, "USPSocketClient is interrupt"); + } + this.mIsStop = true; + } - @Override - protected void finalize() throws Throwable { - close(); - super.finalize(); - } + /** + * close the UDP socket + */ + public synchronized void close() { + if (!this.mIsClosed) { + this.mSocket.close(); + this.mIsClosed = true; + } + } - public void interrupt() { - if (__IEsptouchTask.DEBUG) { - Log.i(TAG, "USPSocketClient is interrupt"); - } - this.mIsStop = true; - } + /** + * send the data by UDP + * + * @param data the data to be sent + * @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); + } - /** - * 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(); - } - } + /** + * 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 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.w(TAG, "sendData(): data == null or length <= 0"); + } + return; + } + for (int i = offset; !mIsStop && i < offset + count; i++) { + if (data[i].length == 0) { + continue; + } + try { + InetAddress targetInetAddress = InetAddress.getByName(targetHostName); + DatagramPacket localDatagramPacket = new DatagramPacket( + data[i], data[i].length, targetInetAddress, targetPort); + this.mSocket.send(localDatagramPacket); + } catch (UnknownHostException e) { + if (__IEsptouchTask.DEBUG) { + Log.w(TAG, "sendData(): UnknownHostException"); + } + e.printStackTrace(); + mIsStop = true; + break; + } catch (IOException e) { + if (__IEsptouchTask.DEBUG) { + Log.w(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.w(TAG, "sendData is Interrupted"); + } + mIsStop = true; + break; + } + } + if (mIsStop) { + close(); + } + } } diff --git a/android/src/main/java/com/espressif/iot/esptouch/udp/UDPSocketServer.java b/android/src/main/java/com/espressif/iot/esptouch/udp/UDPSocketServer.java old mode 100644 new mode 100755 index 5eb3935..049f3ff --- a/android/src/main/java/com/espressif/iot/esptouch/udp/UDPSocketServer.java +++ b/android/src/main/java/com/espressif/iot/esptouch/udp/UDPSocketServer.java @@ -1,152 +1,149 @@ package com.espressif.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.InetSocketAddress; import java.net.SocketException; import java.util.Arrays; -import android.content.Context; -import android.net.wifi.WifiManager; -import android.util.Log; - public class UDPSocketServer { + private static final String TAG = "UDPSocketServer"; + private DatagramSocket mServerSocket; + private Context mContext; + private WifiManager.MulticastLock mLock; + private volatile boolean mIsClosed; - 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; + /** + * 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; + try { + this.mServerSocket = new DatagramSocket(null); + this.mServerSocket.setReuseAddress(true); + this.mServerSocket.bind(new InetSocketAddress(port)); + this.mServerSocket.setSoTimeout(socketTimeout); + } catch (IOException e) { + Log.w(TAG, "IOException"); + e.printStackTrace(); + } + this.mIsClosed = false; + WifiManager manager = (WifiManager) mContext.getApplicationContext() + .getSystemService(Context.WIFI_SERVICE); + mLock = manager.createMulticastLock("test wifi"); + Log.d(TAG, "mServerSocket is created, socket read timeout: " + + socketTimeout + ", port: " + port); + } - private synchronized void acquireLock() { - if (mLock != null && !mLock.isHeld()) { - mLock.acquire(); - } - } + 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) { + 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; + } - /** - * 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(); + DatagramPacket packet = new DatagramPacket(new byte[1], 1); + mServerSocket.receive(packet); + Log.d(TAG, "receive: " + (packet.getData()[0])); + return packet.getData()[0]; + } catch (Exception e) { + e.printStackTrace(); + } + return -1; + } - /** - * 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; - } + /** + * 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(); + DatagramPacket packet = new DatagramPacket(new byte[64], 64); + mServerSocket.receive(packet); + byte[] recDatas = Arrays.copyOf(packet.getData(), packet.getLength()); + Log.d(TAG, "received len : " + recDatas.length); + for (int i = 0; i < recDatas.length; i++) { + Log.w(TAG, "recDatas[" + i + "]:" + recDatas[i]); + } + Log.w(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 (Exception e) { + e.printStackTrace(); + } + return null; + } - public void interrupt() { - Log.i(TAG, "USPSocketServer is interrupt"); - close(); - } + 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; - } - } + public synchronized void close() { + if (!this.mIsClosed) { + Log.w(TAG, "mServerSocket is closed"); + mServerSocket.close(); + releaseLock(); + this.mIsClosed = true; + } + } - @Override - protected void finalize() throws Throwable { - close(); - super.finalize(); - } + @Override + protected void finalize() throws Throwable { + close(); + super.finalize(); + } } diff --git a/android/src/main/java/com/espressif/iot/esptouch/util/ByteUtil.java b/android/src/main/java/com/espressif/iot/esptouch/util/ByteUtil.java old mode 100644 new mode 100755 index 529638b..15c85db --- a/android/src/main/java/com/espressif/iot/esptouch/util/ByteUtil.java +++ b/android/src/main/java/com/espressif/iot/esptouch/util/ByteUtil.java @@ -8,258 +8,233 @@ * 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 * + * @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; - } + public static final String ESPTOUCH_ENCODING_CHARSET = "UTF-8"; - /** - * 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); - } + /** + * 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 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; - } + /** + * 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; + } - /** - * 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 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 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 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; + } - /** - * 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); - } + /** + * Put byte[] into char[]( we treat char[] as uint8[]) + * + * @param destUint8s the char[](uint8[]) array + * @param srcBytes 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]); + } + } - /** - * 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; - } + /** + * 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); + } - /** - * 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); - } + /** + * 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); + } - /** - * 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); - } + /** + * 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; + } - /** - * Generate the random byte to be sent - * - * @return the random byte - */ - private static byte randomByte() { - return (byte) (127 - new Random().nextInt(256)); - } + /** + * 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); + } - /** - * 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; - } + /** + * 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]; + System.arraycopy(bssidBytes, offset, bytes, 0, count); + return parseBssid(bytes); + } - 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) - { + 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]; + for (byte bssidByte : bssidBytes) { + k = 0xff & bssidByte; hexK = Integer.toHexString(k); str = ((k < 16) ? ("0" + hexK) : (hexK)); System.out.println(str); @@ -267,85 +242,82 @@ public static String parseBssid(byte[] bssidBytes) } 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"); - } - } + 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_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_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_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_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")) - { + if (parseBssid(b).equals("0ffe349aa3c4")) { System.out.println("test_parseBssid(): pass"); - } - else - { + } else { System.out.println("test_parseBssid(): fail"); } } - public static void main(String args[]) { - test_convertUint8toByte(); - test_convertChar2Uint8(); - test_splitUint8To2bytes(); - test_combine2bytesToOne(); - test_parseBssid(); - } + public static void main(String args[]) { + test_convertUint8toByte(); + test_convertChar2Uint8(); + test_splitUint8To2bytes(); + test_combine2bytesToOne(); + test_parseBssid(); + } } diff --git a/android/src/main/java/com/espressif/iot/esptouch/util/CRC8.java b/android/src/main/java/com/espressif/iot/esptouch/util/CRC8.java old mode 100644 new mode 100755 index 859d9d2..20b35db --- a/android/src/main/java/com/espressif/iot/esptouch/util/CRC8.java +++ b/android/src/main/java/com/espressif/iot/esptouch/util/CRC8.java @@ -4,64 +4,60 @@ 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; - } + private static final short[] crcTable = new short[256]; + 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; + } + } + + private final short init; + private short value; + + 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/src/main/java/com/espressif/iot/esptouch/util/EspAES.java b/android/src/main/java/com/espressif/iot/esptouch/util/EspAES.java new file mode 100755 index 0000000..b89f476 --- /dev/null +++ b/android/src/main/java/com/espressif/iot/esptouch/util/EspAES.java @@ -0,0 +1,104 @@ +package com.espressif.iot.esptouch.util; + +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +public class EspAES { + private static final String TRANSFORMATION_DEFAULT = "AES/ECB/PKCS5Padding"; + + private final byte[] mKey; + private final byte[] mIV; + private final String mTransformation; + private Cipher mEncryptCipher; + private Cipher mDecryptCipher; + + public EspAES(byte[] key) { + this(key, null, TRANSFORMATION_DEFAULT); + } + + public EspAES(byte[] key, String transformation) { + this(key, null, transformation); + } + + public EspAES(byte[] key, byte[] iv) { + this(key, iv, TRANSFORMATION_DEFAULT); + } + + public EspAES(byte[] key, byte[] iv, String transformation) { + mKey = key; + mIV = iv; + mTransformation = transformation; + + mEncryptCipher = createEncryptCipher(); + mDecryptCipher = createDecryptCipher(); + } + + private Cipher createEncryptCipher() { + try { + Cipher cipher = Cipher.getInstance(mTransformation); + + SecretKeySpec secretKeySpec = new SecretKeySpec(mKey, "AES"); + if (mIV == null) { + cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); + } else { + IvParameterSpec parameterSpec = new IvParameterSpec(mIV); + cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, parameterSpec); + } + + return cipher; + } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException + e) { + e.printStackTrace(); + } + + return null; + } + + private Cipher createDecryptCipher() { + try { + Cipher cipher = Cipher.getInstance(mTransformation); + + SecretKeySpec secretKeySpec = new SecretKeySpec(mKey, "AES"); + if (mIV == null) { + cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); + } else { + IvParameterSpec parameterSpec = new IvParameterSpec(mIV); + cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, parameterSpec); + } + + return cipher; + } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException + e) { + e.printStackTrace(); + } + + return null; + } + + public byte[] encrypt(byte[] content) { + try { + return mEncryptCipher.doFinal(content); + } catch (BadPaddingException | IllegalBlockSizeException e) { + e.printStackTrace(); + } + return null; + } + + public byte[] decrypt(byte[] content) { + try { + return mDecryptCipher.doFinal(content); + } catch (BadPaddingException | IllegalBlockSizeException e) { + e.printStackTrace(); + } + + return null; + } +} diff --git a/android/src/main/java/com/espressif/iot/esptouch/util/EspNetUtil.java b/android/src/main/java/com/espressif/iot/esptouch/util/EspNetUtil.java deleted file mode 100644 index 12ba5f3..0000000 --- a/android/src/main/java/com/espressif/iot/esptouch/util/EspNetUtil.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.espressif.iot.esptouch.util; - -import java.net.InetAddress; -import java.net.UnknownHostException; - -import android.content.Context; -import android.net.wifi.WifiInfo; -import android.net.wifi.WifiManager; -import android.util.Log; -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(":"); - if(bssidSplits.length < 8) { - return new byte[0]; - } - 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/src/main/java/com/espressif/iot/esptouch/util/TouchNetUtil.java b/android/src/main/java/com/espressif/iot/esptouch/util/TouchNetUtil.java new file mode 100755 index 0000000..e9bcf92 --- /dev/null +++ b/android/src/main/java/com/espressif/iot/esptouch/util/TouchNetUtil.java @@ -0,0 +1,123 @@ +package com.espressif.iot.esptouch.util; + +import android.content.Context; +import android.net.wifi.WifiInfo; +import android.net.wifi.WifiManager; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.InetAddress; +import java.net.UnknownHostException; + +public class TouchNetUtil { + + /** + * 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 like aa:bb:cc:dd:ee:ff + * @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; + } + + public static byte[] getOriginalSsidBytes(WifiInfo info) { + try { + Method method = info.getClass().getMethod("getWifiSsid"); + if (method == null) { + return null; + } + method.setAccessible(true); + Object wifiSsid = method.invoke(info); + if (wifiSsid == null) { + return null; + } + method = wifiSsid.getClass().getMethod("getOctets"); + if (method == null) { + return null; + } + method.setAccessible(true); + return (byte[]) method.invoke(wifiSsid); + } catch (NoSuchMethodException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (InvocationTargetException e) { + e.printStackTrace(); + } catch (NullPointerException e) { + e.printStackTrace(); + } + return null; + } +} diff --git a/android/src/main/java/com/tuanpm/RCTSmartconfig/RCTSmartconfigModule.java b/android/src/main/java/com/tuanpm/RCTSmartconfig/RCTSmartconfigModule.java old mode 100644 new mode 100755 index d628597..fbb6ec0 --- a/android/src/main/java/com/tuanpm/RCTSmartconfig/RCTSmartconfigModule.java +++ b/android/src/main/java/com/tuanpm/RCTSmartconfig/RCTSmartconfigModule.java @@ -24,10 +24,12 @@ import java.util.Map; import java.util.List; + import com.espressif.iot.esptouch.EsptouchTask; import com.espressif.iot.esptouch.IEsptouchListener; import com.espressif.iot.esptouch.IEsptouchResult; import com.espressif.iot.esptouch.IEsptouchTask; +import com.espressif.iot.esptouch.util.EspAES; import com.espressif.iot.esptouch.task.__IEsptouchTask; public class RCTSmartconfigModule extends ReactContextBaseJavaModule { @@ -60,9 +62,10 @@ public void stop() { @ReactMethod public void start(final ReadableMap options, final Promise promise) { String ssid = options.getString("ssid"); + String bssid = options.getString("bssid"); String pass = options.getString("password"); + int taskCount = options.getInt("taskCount"); Boolean hidden = false; - //Int taskResultCountStr = 1; Log.d(TAG, "ssid " + ssid + ":pass " + pass); stop(); new EsptouchAsyncTask(new TaskListener() { @@ -73,6 +76,7 @@ public void onFinished(List result) { WritableArray ret = Arguments.createArray(); Boolean resolved = false; + try{ for (IEsptouchResult resultInList : result) { if(!resultInList.isCancelled() &&resultInList.getBssid() != null) { WritableMap map = Arguments.createMap(); @@ -91,11 +95,14 @@ public void onFinished(List result) { promise.resolve(ret); } else { Log.d(TAG, "Error run smartconfig"); - promise.reject("new IllegalViewOperationException()"); + promise.reject("Timeoutout"); + } + }catch(Exception e){ + Log.d(TAG, "Error, Smartconfig could not complete!"); + promise.reject("Timeoutout", e); } - } - }).execute(ssid, new String(""), pass, "YES", "1"); + }).execute(ssid, bssid, pass, Integer.toString(taskCount)); //promise.resolve(encoded); //promise.reject("Error creating media file."); // @@ -136,24 +143,20 @@ protected void onPreExecute() { @Override protected List doInBackground(String... params) { Log.d(TAG, "doing task"); - int taskResultCount = -1; + int taskCount = -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, getCurrentActivity()); - - //mEsptouchTask.setEsptouchListener(myListener); + String apSsidB64 = params[0]; + byte[] apSsid = Base64.decode(apSsidB64, Base64.DEFAULT); + String apBssid64 = params[1]; + byte[] apBssid = Base64.decode(apBssid64, Base64.DEFAULT); + String apPasswordB64 = params[2]; + byte[] apPassword = Base64.decode(apPasswordB64, Base64.DEFAULT); + Log.d(TAG, apSsid + " | " + apBssid + " | " + apPassword); + String taskCountStr = params[3]; + taskCount = Integer.parseInt(taskCountStr); + mEsptouchTask = new EsptouchTask(apSsid, apBssid, apPassword, getCurrentActivity()); } - List resultList = mEsptouchTask.executeForResults(taskResultCount); + List resultList = mEsptouchTask.executeForResults(taskCount); return resultList; } diff --git a/android/src/main/java/com/tuanpm/RCTSmartconfig/RCTSmartconfigPackage.java b/android/src/main/java/com/tuanpm/RCTSmartconfig/RCTSmartconfigPackage.java old mode 100644 new mode 100755 diff --git a/ios/RCTSmartconfig/ESPAES.h b/ios/RCTSmartconfig/ESPAES.h new file mode 100755 index 0000000..82e47ff --- /dev/null +++ b/ios/RCTSmartconfig/ESPAES.h @@ -0,0 +1,19 @@ +// +// ESPAES.h +// EspTouchDemo +// +// Created by AE on 2018/4/5. +// + +#import + +@interface ESPAES : NSObject { + @private NSString *key; +} + +- (instancetype)initWithKey:(NSString *)secretKey; + +- (NSData *)AES128EncryptData:(NSData *)data; +- (NSData *)AES128DecryptData:(NSData *)data; + +@end diff --git a/ios/RCTSmartconfig/ESPAES.m b/ios/RCTSmartconfig/ESPAES.m new file mode 100755 index 0000000..9a3f718 --- /dev/null +++ b/ios/RCTSmartconfig/ESPAES.m @@ -0,0 +1,66 @@ +// +// ESPAES.m +// EspTouchDemo +// +// Created by AE on 2018/4/5. +// + +#import "ESPAES.h" +#import + +@implementation ESPAES + +- (instancetype)initWithKey:(NSString *)secretKey +{ + self = [super init]; + if (self) { + key = secretKey; + } + return self; +} + +- (NSData *)AES128EncryptData:(NSData *)data { + char keyPtr[kCCKeySizeAES128+1]; + bzero(keyPtr, sizeof(keyPtr)); + [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding]; + NSUInteger dataLength = [data length]; + size_t bufferSize = dataLength + kCCBlockSizeAES128; + void *buffer = malloc(bufferSize); + size_t numBytesEncrypted = 0; + CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, + kCCOptionPKCS7Padding | kCCOptionECBMode, + keyPtr, kCCBlockSizeAES128, + NULL, + [data bytes], dataLength, + buffer, bufferSize, + &numBytesEncrypted); + if (cryptStatus == kCCSuccess) { + return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted]; + } + free(buffer); + return nil; +} + +- (NSData *)AES128DecryptData:(NSData *)data { + char keyPtr[kCCKeySizeAES128+1]; + bzero(keyPtr, sizeof(keyPtr)); + [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding]; + NSUInteger dataLength = [data length]; + size_t bufferSize = dataLength + kCCBlockSizeAES128; + void *buffer = malloc(bufferSize); + size_t numBytesDecrypted = 0; + CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, + kCCOptionPKCS7Padding | kCCOptionECBMode, + keyPtr, kCCBlockSizeAES128, + NULL, + [data bytes], dataLength, + buffer, bufferSize, + &numBytesDecrypted); + if (cryptStatus == kCCSuccess) { + return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted]; + } + free(buffer); + return nil; +} + +@end diff --git a/ios/RCTSmartconfig/ESPAppDelegate.m b/ios/RCTSmartconfig/ESPAppDelegate.m index 0cd39f6..99de262 100755 --- a/ios/RCTSmartconfig/ESPAppDelegate.m +++ b/ios/RCTSmartconfig/ESPAppDelegate.m @@ -7,7 +7,6 @@ // #import "ESPAppDelegate.h" -#import "ESPViewController.h" #import "ESP_NetUtil.h" #import @@ -20,7 +19,7 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:( [ESP_NetUtil tryOpenNetworkPermission]; return YES; } - + - (void)applicationWillResignActive:(UIApplication *)application { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. @@ -42,16 +41,6 @@ - (void)applicationWillEnterForeground:(UIApplication *)application // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } -// it is used to show the current connected wifi's Ssid -- (void)applicationDidBecomeActive:(UIApplication *)application -{ - // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. - ESPViewController *vc = (ESPViewController *)self.window.rootViewController; - NSDictionary *netInfo = [self fetchNetInfo]; - vc.ssidLabel.text = [netInfo objectForKey:@"SSID"]; - vc.bssid = [netInfo objectForKey:@"BSSID"]; -} - - (void)applicationWillTerminate:(UIApplication *)application { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. diff --git a/ios/RCTSmartconfig/ESPDatumCode.h b/ios/RCTSmartconfig/ESPDatumCode.h index ca78b39..befc362 100755 --- a/ios/RCTSmartconfig/ESPDatumCode.h +++ b/ios/RCTSmartconfig/ESPDatumCode.h @@ -29,7 +29,7 @@ * whether the Ap's ssid is hidden * */ -- (id) initWithSsid: (NSString *) apSsid andApBssid: (NSString *) apBssid andApPwd: (NSString*) apPwd andInetAddrData: (NSData *) ipAddrData andIsSsidHidden: (BOOL) isSsidHidden; +- (id) initWithSsid: (NSData *) apSsid andApBssid: (NSData *) apBssid andApPwd: (NSData*) apPwd andInetAddrData: (NSData *) ipAddrData andIsSsidHidden: (BOOL) isSsidHidden; - (NSData *) getBytes; diff --git a/ios/RCTSmartconfig/ESPDatumCode.m b/ios/RCTSmartconfig/ESPDatumCode.m index dac3fda..0b0d542 100755 --- a/ios/RCTSmartconfig/ESPDatumCode.m +++ b/ios/RCTSmartconfig/ESPDatumCode.m @@ -18,34 +18,34 @@ @implementation ESPDatumCode -- (id) initWithSsid: (NSString *) apSsid andApBssid: (NSString *) apBssid andApPwd: (NSString*) apPwd andInetAddrData: (NSData *) ipAddrData andIsSsidHidden: (BOOL) isSsidHidden +- (id) initWithSsid: (NSData *) apSsid andApBssid: (NSData *) apBssid andApPwd: (NSData*) apPwd andInetAddrData: (NSData *) ipAddrData andIsSsidHidden: (BOOL) isSsidHidden { self = [super init]; if (self) { // 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 + // BSSID CRC(1 byte) + TOTAL XOR(1 byte) + ipAddress(4 byte) + apPwd + apSsid apPwdLen <= + // 105 at the moment // total xor UInt8 totalXor = 0; - NSData *apPwdBytesData = [ESP_ByteUtil getBytesByNSString:apPwd]; - NSData *apSsidBytesData = [ESP_ByteUtil getBytesByNSString:apSsid]; + NSData *apPwdBytesData = apPwd; + NSData *apSsidBytesData = apSsid; Byte apPwdBytes[[apPwdBytesData length]]; Byte apSsidBytes[[apSsidBytesData length]]; - [apPwdBytesData getBytes:apPwdBytes]; - [apSsidBytesData getBytes:apSsidBytes]; + [apPwdBytesData getBytes:apPwdBytes length:[apPwdBytesData length]]; + [apSsidBytesData getBytes:apSsidBytes length:[apSsidBytesData length]]; Byte apPwdLen = [apPwdBytesData length]; ESP_CRC8 *crc = [[ESP_CRC8 alloc]init]; [crc updateWithBuf:apSsidBytes Nbytes:(int)sizeof(apSsidBytes)]; Byte apSsidCrc = [crc getValue]; [crc reset]; - NSData *apBssidData = [ESP_NetUtil parseBssid2bytes:apBssid]; + NSData *apBssidData = apBssid; int apBssidDataLen = (int)[apBssidData length]; Byte apBssidBytes[apBssidDataLen]; - [apBssidData getBytes:apBssidBytes]; + [apBssidData getBytes:apBssidBytes length:[apBssidData length]]; [crc updateWithBuf:apBssidBytes Nbytes:apBssidDataLen]; UInt8 apBssidCrc = [crc getValue]; @@ -54,14 +54,14 @@ - (id) initWithSsid: (NSString *) apSsid andApBssid: (NSString *) apBssid andApP // only support ipv4 at the moment UInt8 ipLen = [ipAddrData length]; Byte ipAddrUint8s[ipLen]; - [ipAddrData getBytes:ipAddrUint8s]; + [ipAddrData getBytes:ipAddrUint8s length:[ipAddrData length]]; UInt8 _totalLen = EXTRA_HEAD_LEN + ipLen + apPwdLen + apSsidLen; UInt8 totalLen = isSsidHidden ? (EXTRA_HEAD_LEN + ipLen + apPwdLen + apSsidLen):(EXTRA_HEAD_LEN + ipLen + apPwdLen); - // build data codes - _dataCodes = [[NSMutableArray alloc]initWithCapacity:totalLen]; + _dataCodes = [[NSMutableArray alloc]initWithCapacity:totalLen + apBssidDataLen]; + ESPDataCode *dataCode = [[ESPDataCode alloc]initWithU8:_totalLen andIndex:0]; [_dataCodes addObject:dataCode]; totalXor ^= _totalLen; @@ -106,6 +106,20 @@ - (id) initWithSsid: (NSString *) apSsid andApBssid: (NSString *) apBssid andApP // add total xor last dataCode = [[ESPDataCode alloc]initWithU8:totalXor andIndex:4]; [_dataCodes insertObject:dataCode atIndex:4]; + + // add bssid + NSUInteger bssidInsertIndex = EXTRA_HEAD_LEN; + for (int i = 0; i < apBssidDataLen; i++) { + int index = totalLen + i; + Byte b = apBssidBytes[i]; + ESPDataCode *dc = [[ESPDataCode alloc] initWithU8:b andIndex:index]; + if (bssidInsertIndex >= _dataCodes.count) { + [_dataCodes addObject:dc]; + } else { + [_dataCodes insertObject:dc atIndex:bssidInsertIndex]; + } + bssidInsertIndex += 4; + } } return self; } diff --git a/ios/RCTSmartconfig/ESPTouchGenerator.h b/ios/RCTSmartconfig/ESPTouchGenerator.h index 347bb32..81b61a8 100755 --- a/ios/RCTSmartconfig/ESPTouchGenerator.h +++ b/ios/RCTSmartconfig/ESPTouchGenerator.h @@ -29,7 +29,7 @@ * @param isSsidHidden * whether the Ap's ssid is hidden */ -- (id) initWithSsid: (NSString *) apSsid andApBssid: (NSString *) apBssid andApPassword: (NSString *) apPwd andInetAddrData: (NSData *) ipAddrData andIsSsidHidden: (BOOL) isSsidHidden; +- (id) initWithSsid: (NSData *)apSsid andApBssid: (NSData *)apBssid andApPassword: (NSData *)apPwd andInetAddrData: (NSData *)ipAddrData andIsSsidHidden: (BOOL)isSsidHidden; /** * Get guide code by the format of byte[][] diff --git a/ios/RCTSmartconfig/ESPTouchGenerator.m b/ios/RCTSmartconfig/ESPTouchGenerator.m index 05432c4..a011b3b 100755 --- a/ios/RCTSmartconfig/ESPTouchGenerator.m +++ b/ios/RCTSmartconfig/ESPTouchGenerator.m @@ -14,7 +14,7 @@ @implementation ESPTouchGenerator -- (id) initWithSsid: (NSString *) apSsid andApBssid: (NSString *) apBssid andApPassword: (NSString *) apPwd andInetAddrData: (NSData *) ipAddrData andIsSsidHidden: (BOOL) isSsidHidden +- (id) initWithSsid: (NSData *)apSsid andApBssid: (NSData *)apBssid andApPassword: (NSData *)apPwd andInetAddrData: (NSData *)ipAddrData andIsSsidHidden:(BOOL) isSsidHidden { self = [super init]; if (self) diff --git a/ios/RCTSmartconfig/ESPTouchTask.h b/ios/RCTSmartconfig/ESPTouchTask.h index 65fa27e..c1e7ae5 100755 --- a/ios/RCTSmartconfig/ESPTouchTask.h +++ b/ios/RCTSmartconfig/ESPTouchTask.h @@ -9,6 +9,9 @@ #import #import "ESPTouchResult.h" #import "ESPTouchDelegate.h" +#import "ESPAES.h" + +#define ESPTOUCH_VERSION @"v0.3.7.1" #define DEBUG_ON YES @@ -28,7 +31,7 @@ * @param isSsidHidden * whether the Ap's ssid is hidden */ -- (id) initWithApSsid: (NSString *)apSsid andApBssid: (NSString *) apBssid andApPwd: (NSString *)apPwd andIsSsidHiden: (BOOL) isSsidHidden; +- (id) initWithApSsid: (NSString *)apSsid andApBssid: (NSString *) apBssid andApPwd: (NSString *)apPwd; /** * Constructor of EsptouchTask @@ -46,7 +49,7 @@ * @param context * the Context of the Application */ -- (id) initWithApSsid: (NSString *)apSsid andApBssid: (NSString *) apBssid andApPwd: (NSString *)apPwd andIsSsidHiden: (BOOL) isSsidHidden andTimeoutMillisecond: (int) timeoutMillisecond; +- (id) initWithApSsid: (NSString *)apSsid andApBssid: (NSString *) apBssid andApPwd: (NSString *)apPwd andTimeoutMillisecond: (int) timeoutMillisecond; /** * Interrupt the Esptouch Task when User tap back or close the Application. @@ -87,4 +90,9 @@ */ - (void) setEsptouchDelegate: (NSObject *) esptouchDelegate; +/** + * Set boradcast or multicast when post config info + * @param broadcast YES is boradcast, NO is multicast + */ +- (void) setPackageBroadcast: (BOOL) broadcast; @end diff --git a/ios/RCTSmartconfig/ESPTouchTask.m b/ios/RCTSmartconfig/ESPTouchTask.m index 2bc6b33..994bfe0 100755 --- a/ios/RCTSmartconfig/ESPTouchTask.m +++ b/ios/RCTSmartconfig/ESPTouchTask.m @@ -15,19 +15,16 @@ #import "ESPUDPSocketServer.h" #import "ESP_NetUtil.h" #import "ESPTouchTaskParameter.h" -#import -#import #define ONE_DATA_LEN 3 -#define ESPTOUCH_VERSION @"v0.3.5.2" @interface ESPTouchTask () -@property (nonatomic,strong) NSString *_apSsid; +@property (nonatomic,strong) NSData *_apSsid; -@property (nonatomic,strong) NSString *_apBssid; +@property (nonatomic,strong) NSData *_apBssid; -@property (nonatomic,strong) NSString *_apPwd; +@property (nonatomic,strong) NSData *_apPwd; @property (atomic,assign) BOOL _isSuc; @@ -53,8 +50,6 @@ @interface ESPTouchTask () @property (atomic,strong) NSCondition *_esptouchResultArrayCondition; -@property (nonatomic,assign) __block UIBackgroundTaskIdentifier _backgroundTask; - @property (nonatomic,strong) id _esptouchDelegate; @property (nonatomic,strong) NSData *_localInetAddrData; @@ -63,7 +58,7 @@ @interface ESPTouchTask () @implementation ESPTouchTask -- (id) initWithApSsid: (NSString *)apSsid andApBssid: (NSString *) apBssid andApPwd: (NSString *)apPwd andIsSsidHiden: (BOOL) isSsidHidden +- (id)initWithApSsid:(NSString *)apSsid andApBssid:(NSString *)apBssid andApPwd:(NSString *)apPwd andAES:(ESPAES *)aes { NSLog(@"Welcome Esptouch %@",ESPTOUCH_VERSION); if (apSsid==nil||[apSsid isEqualToString:@""]) @@ -84,9 +79,14 @@ - (id) initWithApSsid: (NSString *)apSsid andApBssid: (NSString *) apBssid andAp { NSLog(@"ESPTouchTask init"); } - self._apSsid = apSsid; - self._apPwd = apPwd; - self._apBssid = apBssid; + if (aes == nil) { + self._apSsid = [ESP_ByteUtil getBytesByNSString:apSsid]; + self._apPwd = [ESP_ByteUtil getBytesByNSString:apPwd]; + } else { + self._apSsid = [aes AES128EncryptData:[ESP_ByteUtil getBytesByNSString:apSsid]]; + self._apPwd = [aes AES128EncryptData:[ESP_ByteUtil getBytesByNSString:apPwd]]; + } + self._apBssid = [ESP_NetUtil parseBssid2bytes:apBssid]; self._parameter = [[ESPTaskParameter alloc]init]; // check whether IPv4 and IPv6 is supported @@ -126,7 +126,7 @@ - (id) initWithApSsid: (NSString *)apSsid andApBssid: (NSString *) apBssid andAp self._isWakeUp = NO; self._isExecutedAlready = NO; self._condition = [[NSCondition alloc]init]; - self._isSsidHidden = isSsidHidden; + self._isSsidHidden = YES; self._esptouchResultArray = [[NSMutableArray alloc]init]; self._bssidTaskSucCountDict = [[NSMutableDictionary alloc]init]; self._esptouchResultArrayCondition = [[NSCondition alloc]init]; @@ -134,9 +134,21 @@ - (id) initWithApSsid: (NSString *)apSsid andApBssid: (NSString *) apBssid andAp return self; } -- (id) initWithApSsid: (NSString *)apSsid andApBssid: (NSString *) apBssid andApPwd: (NSString *)apPwd andIsSsidHiden: (BOOL) isSsidHidden andTimeoutMillisecond: (int) timeoutMillisecond +- (id) initWithApSsid: (NSString *)apSsid andApBssid: (NSString *) apBssid andApPwd: (NSString *)apPwd { + return [self initWithApSsid:apSsid andApBssid:apBssid andApPwd:apPwd andAES:nil]; +} + +- (id) initWithApSsid: (NSString *)apSsid andApBssid: (NSString *) apBssid andApPwd: (NSString *)apPwd andIsSsidHiden: (BOOL) isSsidHidden +{ + return [self initWithApSsid:apSsid andApBssid:apBssid andApPwd:apPwd]; +} + +- (id) initWithApSsid: (NSString *)apSsid andApBssid: (NSString *) apBssid andApPwd: (NSString *)apPwd andTimeoutMillisecond: (int) timeoutMillisecond { - ESPTouchTask *_self = [self initWithApSsid:apSsid andApBssid:apBssid andApPwd:apPwd andIsSsidHiden:isSsidHidden]; + NSLog(@"apSsid %@",apSsid); + NSLog(@"apBssid %@",apBssid); + NSLog(@"apPwd %@",apPwd); + ESPTouchTask *_self = [self initWithApSsid:apSsid andApBssid:apBssid andApPwd:apPwd]; if (_self) { [_self._parameter setWaitUdpTotalMillisecond:timeoutMillisecond]; @@ -220,13 +232,6 @@ - (void) beginBackgroundTask { NSLog(@"ESPTouchTask beginBackgroundTask() entrance"); } - self._backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ - if (DEBUG_ON) - { - NSLog(@"ESPTouchTask beginBackgroundTask() endBackgroundTask"); - } - [self endBackgroundTask]; - }]; } - (void) endBackgroundTask @@ -235,8 +240,6 @@ - (void) endBackgroundTask { NSLog(@"ESPTouchTask endBackgroundTask() entrance"); } - [[UIApplication sharedApplication] endBackgroundTask: self._backgroundTask]; - self._backgroundTask = UIBackgroundTaskInvalid; } - (void) __listenAsyn: (const int) expectDataLen @@ -249,8 +252,8 @@ - (void) __listenAsyn: (const int) expectDataLen NSLog(@"ESPTouchTask __listenAsyn() start an asyn listen task, current thread is: %@", [NSThread currentThread]); } NSTimeInterval startTimestamp = [[NSDate date] timeIntervalSince1970]; - NSString *apSsidAndPwd = [NSString stringWithFormat:@"%@%@",self._apSsid,self._apPwd]; - Byte expectOneByte = [ESP_ByteUtil getBytesByNSString:apSsidAndPwd].length + 9; +// NSString *apSsidAndPwd = [NSString stringWithFormat:@"%@%@",self._apSsid,self._apPwd]; + Byte expectOneByte = [self._apSsid length] + [self._apPwd length] + 9; if (DEBUG_ON) { NSLog(@"ESPTouchTask __listenAsyn() expectOneByte: %d",expectOneByte); @@ -496,4 +499,8 @@ - (void) setEsptouchDelegate: (NSObject *) esptouchDelegate self._esptouchDelegate = esptouchDelegate; } +- (void)setPackageBroadcast:(BOOL)broadcast { + [self._parameter setBroadcast:broadcast]; +} + @end diff --git a/ios/RCTSmartconfig/ESPTouchTaskParameter.h b/ios/RCTSmartconfig/ESPTouchTaskParameter.h index 33fcb24..5bd8c69 100755 --- a/ios/RCTSmartconfig/ESPTouchTaskParameter.h +++ b/ios/RCTSmartconfig/ESPTouchTaskParameter.h @@ -165,4 +165,9 @@ */ - (void) setListeningPort6:(int) listeningPort6; +/** + * Set broadcast or multicast + */ +- (void) setBroadcast:(BOOL) broadcast; + @end diff --git a/ios/RCTSmartconfig/ESPTouchTaskParameter.m b/ios/RCTSmartconfig/ESPTouchTaskParameter.m index 159470e..03d51b5 100755 --- a/ios/RCTSmartconfig/ESPTouchTaskParameter.m +++ b/ios/RCTSmartconfig/ESPTouchTaskParameter.m @@ -31,6 +31,7 @@ @interface ESPTaskParameter() @property (nonatomic,assign) int expectTaskResultCount; @property (nonatomic,assign) BOOL isIPv4Supported0; @property (nonatomic,assign) BOOL isIPv6Supported0; +@property (nonatomic,assign) BOOL broadcast; @end @implementation ESPTaskParameter @@ -41,8 +42,8 @@ - (id) init { self = [super init]; if (self) { - self.intervalGuideCodeMillisecond = 10; - self.intervalDataCodeMillisecond = 10; + self.intervalGuideCodeMillisecond = 8; + self.intervalDataCodeMillisecond = 8; self.timeoutGuideCodeMillisecond = 2000; self.timeoutDataCodeMillisecond = 4000; self.timeoutTotalCodeMillisecond = 2000 + 4000; @@ -145,8 +146,12 @@ - (int) getPortListening - (NSString *) getTargetHostname { if (_isIPv4Supported0) { - int count = [self __getNextDatagramCount]; - return [NSString stringWithFormat: @"234.%d.%d.%d", count, count, count]; + if (self.broadcast) { + return @"255.255.255.255"; + } else { + int count = [self __getNextDatagramCount]; + return [NSString stringWithFormat: @"234.%d.%d.%d", count, count, count]; + } } else { return @"ff02::1%en0"; } @@ -227,4 +232,8 @@ - (void) setListeningPort6:(int) listeningPort6 _portListening6 = listeningPort6; } +- (void)setBroadcast:(BOOL)broadcast { + _broadcast = broadcast; +} + @end diff --git a/ios/RCTSmartconfig/ESPViewController.h b/ios/RCTSmartconfig/ESPViewController.h index 426d3d3..f9793fc 100755 --- a/ios/RCTSmartconfig/ESPViewController.h +++ b/ios/RCTSmartconfig/ESPViewController.h @@ -9,6 +9,9 @@ #import @interface ESPViewController : UIViewController + @property (weak, nonatomic) IBOutlet UILabel *ssidLabel; -@property (strong, nonatomic) NSString *bssid; +@property (weak, nonatomic) IBOutlet UILabel *bssidLabel; +@property (weak, nonatomic) IBOutlet UISegmentedControl *broadcastSC; + @end diff --git a/ios/RCTSmartconfig/ESPViewController.m b/ios/RCTSmartconfig/ESPViewController.m new file mode 100755 index 0000000..44ced28 --- /dev/null +++ b/ios/RCTSmartconfig/ESPViewController.m @@ -0,0 +1,300 @@ +// +// ESPViewController.m +// EspTouchDemo +// +// Created by 白 桦 on 3/23/15. +// Copyright (c) 2015 白 桦. All rights reserved. +// + +#import "ESPViewController.h" +#import "ESPTouchTask.h" +#import "ESPTouchResult.h" +#import "ESP_NetUtil.h" +#import "ESPTouchDelegate.h" +#import "ESPAES.h" + +#import + +// the three constants are used to hide soft-keyboard when user tap Enter or Return +#define HEIGHT_KEYBOARD 216 +#define HEIGHT_TEXT_FIELD 30 +#define HEIGHT_SPACE (6+HEIGHT_TEXT_FIELD) + +@interface EspTouchDelegateImpl : NSObject + +@end + +@implementation EspTouchDelegateImpl + +-(void) dismissAlert:(UIAlertView *)alertView +{ + [alertView dismissWithClickedButtonIndex:[alertView cancelButtonIndex] animated:YES]; +} + +-(void) showAlertWithResult: (ESPTouchResult *) result +{ + NSString *title = nil; + NSString *message = [NSString stringWithFormat:@"%@ is connected to the wifi" , result.bssid]; + NSTimeInterval dismissSeconds = 3.5; + UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:title message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:nil]; + [alertView show]; + [self performSelector:@selector(dismissAlert:) withObject:alertView afterDelay:dismissSeconds]; +} + +-(void) onEsptouchResultAddedWithResult: (ESPTouchResult *) result +{ + NSLog(@"EspTouchDelegateImpl onEsptouchResultAddedWithResult bssid: %@", result.bssid); + dispatch_async(dispatch_get_main_queue(), ^{ + [self showAlertWithResult:result]; + }); +} + +@end + +@interface ESPViewController () + +@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *_spinner; +@property (weak, nonatomic) IBOutlet UITextField *_pwdTextView; +@property (weak, nonatomic) IBOutlet UITextField *_taskResultCountTextView; +@property (weak, nonatomic) IBOutlet UIButton *_confirmCancelBtn; +@property (weak, nonatomic) IBOutlet UILabel *_versionLabel; + +// to cancel ESPTouchTask when +@property (atomic, strong) ESPTouchTask *_esptouchTask; + +// the state of the confirm/cancel button +@property (nonatomic, assign) BOOL _isConfirmState; + +// without the condition, if the user tap confirm/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 +@property (nonatomic, strong) NSCondition *_condition; + +@property (nonatomic, strong) UIButton *_doneButton; +@property (nonatomic, strong) EspTouchDelegateImpl *_esptouchDelegate; + +@end + +@implementation ESPViewController + +- (IBAction)tapConfirmCancelBtn:(UIButton *)sender +{ + [self tapConfirmForResults]; +} + + +- (void) tapConfirmForResults +{ + // do confirm + if (self._isConfirmState) + { + NSString *apSsid = self.ssidLabel.text; + NSString *apPwd = self._pwdTextView.text; + NSString *apBssid = self.bssidLabel.text; + int taskCount = [self._taskResultCountTextView.text intValue]; + BOOL broadcast = self.broadcastSC.selectedSegmentIndex == 0 ? YES : NO; + + [self._spinner startAnimating]; + [self enableCancelBtn]; + NSLog(@"ESPViewController do confirm action..."); + dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); + dispatch_async(queue, ^{ + NSLog(@"ESPViewController do the execute work..."); + // execute the task + NSArray *esptouchResultArray = [self executeForResultsWithSsid:apSsid bssid:apBssid password:apPwd taskCount:taskCount broadcast:broadcast]; + // show the result to the user in UI Main Thread + dispatch_async(dispatch_get_main_queue(), ^{ + [self._spinner stopAnimating]; + [self enableConfirmBtn]; + + ESPTouchResult *firstResult = [esptouchResultArray objectAtIndex:0]; + // check whether the task is cancelled and no results received + if (!firstResult.isCancelled) + { + NSMutableString *mutableStr = [[NSMutableString alloc]init]; + NSUInteger count = 0; + // max results to be displayed, if it is more than maxDisplayCount, + // just show the count of redundant ones + const int maxDisplayCount = 5; + if ([firstResult isSuc]) + { + + for (int i = 0; i < [esptouchResultArray count]; ++i) + { + ESPTouchResult *resultInArray = [esptouchResultArray objectAtIndex:i]; + [mutableStr appendString:[resultInArray description]]; + [mutableStr appendString:@"\n"]; + count++; + if (count >= maxDisplayCount) + { + break; + } + } + + if (count < [esptouchResultArray count]) + { + [mutableStr appendString:[NSString stringWithFormat:@"\nthere's %lu more result(s) without showing\n",(unsigned long)([esptouchResultArray count] - count)]]; + } + [[[UIAlertView alloc]initWithTitle:@"Execute Result" message:mutableStr delegate:nil cancelButtonTitle:@"I know" otherButtonTitles:nil]show]; + } + + else + { + [[[UIAlertView alloc]initWithTitle:@"Execute Result" message:@"Esptouch fail" delegate:nil cancelButtonTitle:@"I know" otherButtonTitles:nil]show]; + } + } + + }); + }); + } + // do cancel + else + { + [self._spinner stopAnimating]; + [self enableConfirmBtn]; + NSLog(@"ESPViewController do cancel action..."); + [self cancel]; + } +} + +#pragma mark - the example of how to cancel the executing task + +- (void) cancel +{ + [self._condition lock]; + if (self._esptouchTask != nil) + { + [self._esptouchTask interrupt]; + } + [self._condition unlock]; +} + +#pragma mark - the example of how to use executeForResults +- (NSArray *) executeForResultsWithSsid:(NSString *)apSsid bssid:(NSString *)apBssid password:(NSString *)apPwd taskCount:(int)taskCount broadcast:(BOOL)broadcast +{ + [self._condition lock]; + self._esptouchTask = [[ESPTouchTask alloc]initWithApSsid:apSsid andApBssid:apBssid andApPwd:apPwd]; + // set delegate + [self._esptouchTask setEsptouchDelegate:self._esptouchDelegate]; + [self._esptouchTask setPackageBroadcast:broadcast]; + [self._condition unlock]; + NSArray * esptouchResults = [self._esptouchTask executeForResults:taskCount]; + NSLog(@"ESPViewController executeForResult() result is: %@",esptouchResults); + return esptouchResults; +} + +// enable confirm button +- (void)enableConfirmBtn +{ + self._isConfirmState = YES; + [self._confirmCancelBtn setTitle:@"Confirm" forState:UIControlStateNormal]; +} + +// enable cancel button +- (void)enableCancelBtn +{ + self._isConfirmState = NO; + [self._confirmCancelBtn setTitle:@"Cancel" forState:UIControlStateNormal]; +} + +- (void)viewDidLoad +{ + [super viewDidLoad]; + // Do any additional setup after loading the view, typically from a nib. + self._isConfirmState = NO; + self._pwdTextView.delegate = self; + self._pwdTextView.keyboardType = UIKeyboardTypeASCIICapable; + self._taskResultCountTextView.delegate = self; + self._taskResultCountTextView.keyboardType = UIKeyboardTypeNumberPad; + self._condition = [[NSCondition alloc]init]; + self._esptouchDelegate = [[EspTouchDelegateImpl alloc]init]; + self._versionLabel.text = ESPTOUCH_VERSION; + [self enableConfirmBtn]; +} + +#pragma mark - the follow codes are just to make soft-keyboard disappear at necessary time + +// when out of pwd textview, resign the keyboard +- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event +{ + if (![self._pwdTextView isExclusiveTouch]) + { + [self._pwdTextView resignFirstResponder]; + } + if (![self._taskResultCountTextView isExclusiveTouch]) { + [self._taskResultCountTextView resignFirstResponder]; + } +} + +#pragma mark - the follow three methods are used to make soft-keyboard disappear when user finishing editing + +// when textField begin editing, soft-keyboard apeear, do the callback +-(void)textFieldDidBeginEditing:(UITextField *)textField +{ + CGRect frame = textField.frame; + int offset = frame.origin.y - (self.view.frame.size.height - (HEIGHT_KEYBOARD+HEIGHT_SPACE)); + + NSTimeInterval animationDuration = 0.30f; + [UIView beginAnimations:@"ResizeForKeyboard" context:nil]; + [UIView setAnimationDuration:animationDuration]; + + if(offset > 0) + { + self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height); + } + + [UIView commitAnimations]; +} + +// when user tap Enter or Return, disappear the keyboard +-(BOOL)textFieldShouldReturn:(UITextField *)textField +{ + [textField resignFirstResponder]; + return YES; +} + +// when finish editing, make view restore origin state +-(void)textFieldDidEndEditing:(UITextField *)textField +{ + self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height); +} + +- (void) addButtonToKeyboard { + // create custom button + if (self._doneButton == nil) { + self._doneButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 163, 106, 53)]; + } + else { + [self._doneButton setHidden:NO]; + } + + [self._doneButton addTarget:self action:@selector(doneButtonClicked:) forControlEvents:UIControlEventTouchUpInside]; + // locate keyboard view + UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1]; + UIView* keyboard = nil; + for(int i=0; i<[tempWindow.subviews count]; i++) { + keyboard = [tempWindow.subviews objectAtIndex:i]; + // keyboard found, add the button + if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) { + if([[keyboard description] hasPrefix:@"CFBundleDevelopmentRegion en CFBundleDisplayName - ${PRODUCT_NAME} + Esptouch CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier - com.espressif.iot.${PRODUCT_NAME:rfc1034identifier} + $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName @@ -17,11 +17,11 @@ CFBundlePackageType APPL CFBundleShortVersionString - 1.0 + 1.3.0 CFBundleSignature ???? CFBundleVersion - 1.0 + 1.0.1 LSRequiresIPhoneOS UIMainStoryboardFile diff --git a/ios/RCTSmartconfig/IPAddress.c b/ios/RCTSmartconfig/IPAddress.c deleted file mode 100644 index f32d4b8..0000000 --- a/ios/RCTSmartconfig/IPAddress.c +++ /dev/null @@ -1,216 +0,0 @@ -// -// IPAddress.c -// LocalIpDemo -// -// Created by 白 桦 on 5/11/15. -// Copyright (c) 2015 白 桦. All rights reserved. -// -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "IPAddress.h" - -#define min(a,b) ((a) < (b) ? (a) : (b)) -#define max(a,b) ((a) > (b) ? (a) : (b)) - -#define BUFFERSIZE 4000 - -char *if_names[MAXADDRS]; -char *ip_names[MAXADDRS]; -char *hw_addrs[MAXADDRS]; -unsigned long ip_addrs[MAXADDRS]; - -static int nextAddr = 0; - -void InitAddresses() -{ - int i; - for (i=0; iifr_addr.sa_len); - ptr += sizeof(ifr->ifr_name) + len; // for next one in buffer - - if (ifr->ifr_addr.sa_family != AF_INET) - { - continue; // ignore if not desired address family - } - - if ((cptr = (char *)strchr(ifr->ifr_name, ':')) != NULL) - { - *cptr = 0; // replace colon will null - } - - if (strncmp(lastname, ifr->ifr_name, IFNAMSIZ) == 0) - { - continue; /* already processed this interface */ - } - - memcpy(lastname, ifr->ifr_name, IFNAMSIZ); - - ifrcopy = *ifr; - ioctl(sockfd, SIOCGIFFLAGS, &ifrcopy); - flags = ifrcopy.ifr_flags; - if ((flags & IFF_UP) == 0) - { - continue; // ignore if interface not up - } - - if_names[nextAddr] = (char *)malloc(strlen(ifr->ifr_name)+1); - if (if_names[nextAddr] == NULL) - { - return; - } - strcpy(if_names[nextAddr], ifr->ifr_name); - - sin = (struct sockaddr_in *)&ifr->ifr_addr; - strcpy(temp, inet_ntoa(sin->sin_addr)); - - ip_names[nextAddr] = (char *)malloc(strlen(temp)+1); - if (ip_names[nextAddr] == NULL) - { - return; - } - strcpy(ip_names[nextAddr], temp); - - ip_addrs[nextAddr] = sin->sin_addr.s_addr; - - ++nextAddr; - } - - close(sockfd); -} - -void GetHWAddresses() -{ - struct ifconf ifc; - struct ifreq *ifr; - int i, sockfd; - char buffer[BUFFERSIZE], *cp, *cplim; - char temp[80]; - - for (i=0; iifr_addr.sa_family == AF_LINK) - { - struct sockaddr_dl *sdl = (struct sockaddr_dl *)&ifr->ifr_addr; - int a,b,c,d,e,f; - int i; - - strcpy(temp, (char *)ether_ntoa((const struct ether_addr *)LLADDR(sdl))); - sscanf(temp, "%x:%x:%x:%x:%x:%x", &a, &b, &c, &d, &e, &f); - sprintf(temp, "%02X:%02X:%02X:%02X:%02X:%02X",a,b,c,d,e,f); - - for (i=0; iifr_name, if_names[i]) == 0)) - { - if (hw_addrs[i] == NULL) - { - hw_addrs[i] = (char *)malloc(strlen(temp)+1); - strcpy(hw_addrs[i], temp); - break; - } - } - } - } - cp += sizeof(ifr->ifr_name) + max(sizeof(ifr->ifr_addr), ifr->ifr_addr.sa_len); - } - close(sockfd); -} diff --git a/ios/RCTSmartconfig/IPAddress.h b/ios/RCTSmartconfig/IPAddress.h deleted file mode 100644 index fbbb49e..0000000 --- a/ios/RCTSmartconfig/IPAddress.h +++ /dev/null @@ -1,26 +0,0 @@ -// -// IPAddress.h -// LocalIpDemo -// -// Created by 白 桦 on 5/11/15. -// Copyright (c) 2015 白 桦. All rights reserved. -// - -#ifndef LocalIpDemo_IPAddress_h -#define LocalIpDemo_IPAddress_h - -#define MAXADDRS 32 - -extern char *if_names[MAXADDRS]; -extern char *ip_names[MAXADDRS]; -extern char *hw_addrs[MAXADDRS]; -extern unsigned long ip_addrs[MAXADDRS]; - -// Function prototypes - -void InitAddresses(); -void FreeAddresses(); -void GetIPAddresses(); -void GetHWAddresses(); - -#endif diff --git a/ios/RCTSmartconfig/RCTSmartconfig.xcodeproj/project.pbxproj b/ios/RCTSmartconfig/RCTSmartconfig.xcodeproj/project.pbxproj index 94d722b..65f85c9 100644 --- a/ios/RCTSmartconfig/RCTSmartconfig.xcodeproj/project.pbxproj +++ b/ios/RCTSmartconfig/RCTSmartconfig.xcodeproj/project.pbxproj @@ -7,6 +7,8 @@ objects = { /* Begin PBXBuildFile section */ + 07149B0522B3B12C00AD1203 /* ESPAES.m in Sources */ = {isa = PBXBuildFile; fileRef = 07149B0422B3B12C00AD1203 /* ESPAES.m */; }; + 07149B0822B3B13B00AD1203 /* ESPAppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 07149B0722B3B13B00AD1203 /* ESPAppDelegate.m */; }; FF5CEED91E4DE5EC002ADEB9 /* ESP_WifiUtil.m in Sources */ = {isa = PBXBuildFile; fileRef = FF5CEED81E4DE5EC002ADEB9 /* ESP_WifiUtil.m */; }; FFFA35151C5DD1E300ED832B /* Smartconfig.m in Sources */ = {isa = PBXBuildFile; fileRef = FFFA35141C5DD1E300ED832B /* Smartconfig.m */; }; FFFA354F1C5E01B800ED832B /* ESP_ByteUtil.m in Sources */ = {isa = PBXBuildFile; fileRef = FFFA35331C5E01B800ED832B /* ESP_ByteUtil.m */; }; @@ -21,7 +23,6 @@ FFFA35591C5E01B800ED832B /* ESPTouchTaskParameter.m in Sources */ = {isa = PBXBuildFile; fileRef = FFFA35481C5E01B800ED832B /* ESPTouchTaskParameter.m */; }; FFFA355A1C5E01B800ED832B /* ESPUDPSocketClient.m in Sources */ = {isa = PBXBuildFile; fileRef = FFFA354A1C5E01B800ED832B /* ESPUDPSocketClient.m */; }; FFFA355B1C5E01B800ED832B /* ESPUDPSocketServer.m in Sources */ = {isa = PBXBuildFile; fileRef = FFFA354C1C5E01B800ED832B /* ESPUDPSocketServer.m */; }; - FFFA355C1C5E01B800ED832B /* IPAddress.c in Sources */ = {isa = PBXBuildFile; fileRef = FFFA354D1C5E01B800ED832B /* IPAddress.c */; }; /* End PBXBuildFile section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -37,6 +38,11 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + 07149B0222B3B11A00AD1203 /* ESPVersionMacro.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ESPVersionMacro.h; sourceTree = ""; }; + 07149B0322B3B12B00AD1203 /* ESPAES.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ESPAES.h; sourceTree = ""; }; + 07149B0422B3B12C00AD1203 /* ESPAES.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ESPAES.m; sourceTree = ""; }; + 07149B0622B3B13B00AD1203 /* ESPAppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ESPAppDelegate.h; sourceTree = ""; }; + 07149B0722B3B13B00AD1203 /* ESPAppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ESPAppDelegate.m; sourceTree = ""; }; FF5CEED71E4DE5EC002ADEB9 /* ESP_WifiUtil.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ESP_WifiUtil.h; sourceTree = ""; }; FF5CEED81E4DE5EC002ADEB9 /* ESP_WifiUtil.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ESP_WifiUtil.m; sourceTree = ""; }; FFFA34DC1C5D210D00ED832B /* libRCTSmartconfig.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libRCTSmartconfig.a; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -67,8 +73,6 @@ FFFA354A1C5E01B800ED832B /* ESPUDPSocketClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ESPUDPSocketClient.m; sourceTree = ""; }; FFFA354B1C5E01B800ED832B /* ESPUDPSocketServer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ESPUDPSocketServer.h; sourceTree = ""; }; FFFA354C1C5E01B800ED832B /* ESPUDPSocketServer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ESPUDPSocketServer.m; sourceTree = ""; }; - FFFA354D1C5E01B800ED832B /* IPAddress.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = IPAddress.c; sourceTree = ""; }; - FFFA354E1C5E01B800ED832B /* IPAddress.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = IPAddress.h; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -82,38 +86,81 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - FFFA34D31C5D210D00ED832B = { + 0728C71322B39AB8005375E1 /* esptouch */ = { + isa = PBXGroup; + children = ( + FFFA35451C5E01B800ED832B /* ESPTouchTask.h */, + FFFA35431C5E01B800ED832B /* ESPTouchResult.h */, + FFFA35401C5E01B800ED832B /* ESPTouchDelegate.h */, + ); + name = esptouch; + sourceTree = ""; + }; + 0728C71422B39B46005375E1 /* protocol */ = { isa = PBXGroup; children = ( - FF5CEED71E4DE5EC002ADEB9 /* ESP_WifiUtil.h */, - FF5CEED81E4DE5EC002ADEB9 /* ESP_WifiUtil.m */, - FFFA35321C5E01B800ED832B /* ESP_ByteUtil.h */, - FFFA35331C5E01B800ED832B /* ESP_ByteUtil.m */, - FFFA35341C5E01B800ED832B /* ESP_CRC8.h */, - FFFA35351C5E01B800ED832B /* ESP_CRC8.m */, - FFFA35361C5E01B800ED832B /* ESP_NetUtil.h */, - FFFA35371C5E01B800ED832B /* ESP_NetUtil.m */, - FFFA353A1C5E01B800ED832B /* ESPDataCode.h */, FFFA353B1C5E01B800ED832B /* ESPDataCode.m */, + FFFA353A1C5E01B800ED832B /* ESPDataCode.h */, FFFA353C1C5E01B800ED832B /* ESPDatumCode.h */, FFFA353D1C5E01B800ED832B /* ESPDatumCode.m */, - FFFA353E1C5E01B800ED832B /* ESPGuideCode.h */, - FFFA353F1C5E01B800ED832B /* ESPGuideCode.m */, - FFFA35401C5E01B800ED832B /* ESPTouchDelegate.h */, FFFA35411C5E01B800ED832B /* ESPTouchGenerator.h */, FFFA35421C5E01B800ED832B /* ESPTouchGenerator.m */, - FFFA35431C5E01B800ED832B /* ESPTouchResult.h */, - FFFA35441C5E01B800ED832B /* ESPTouchResult.m */, - FFFA35451C5E01B800ED832B /* ESPTouchTask.h */, - FFFA35461C5E01B800ED832B /* ESPTouchTask.m */, - FFFA35471C5E01B800ED832B /* ESPTouchTaskParameter.h */, - FFFA35481C5E01B800ED832B /* ESPTouchTaskParameter.m */, + FFFA353E1C5E01B800ED832B /* ESPGuideCode.h */, + FFFA353F1C5E01B800ED832B /* ESPGuideCode.m */, + ); + name = protocol; + sourceTree = ""; + }; + 0728C71522B39B78005375E1 /* util */ = { + isa = PBXGroup; + children = ( + 07149B0222B3B11A00AD1203 /* ESPVersionMacro.h */, + FFFA35341C5E01B800ED832B /* ESP_CRC8.h */, + FFFA35351C5E01B800ED832B /* ESP_CRC8.m */, + FFFA35321C5E01B800ED832B /* ESP_ByteUtil.h */, + FFFA35331C5E01B800ED832B /* ESP_ByteUtil.m */, + FFFA35361C5E01B800ED832B /* ESP_NetUtil.h */, + FFFA35371C5E01B800ED832B /* ESP_NetUtil.m */, + FF5CEED71E4DE5EC002ADEB9 /* ESP_WifiUtil.h */, + FF5CEED81E4DE5EC002ADEB9 /* ESP_WifiUtil.m */, + 07149B0322B3B12B00AD1203 /* ESPAES.h */, + 07149B0422B3B12C00AD1203 /* ESPAES.m */, + ); + name = util; + sourceTree = ""; + }; + 0728C71622B39BA7005375E1 /* udp */ = { + isa = PBXGroup; + children = ( FFFA35491C5E01B800ED832B /* ESPUDPSocketClient.h */, FFFA354A1C5E01B800ED832B /* ESPUDPSocketClient.m */, FFFA354B1C5E01B800ED832B /* ESPUDPSocketServer.h */, FFFA354C1C5E01B800ED832B /* ESPUDPSocketServer.m */, - FFFA354D1C5E01B800ED832B /* IPAddress.c */, - FFFA354E1C5E01B800ED832B /* IPAddress.h */, + ); + name = udp; + sourceTree = ""; + }; + 0728C71722B39BB6005375E1 /* task */ = { + isa = PBXGroup; + children = ( + FFFA35461C5E01B800ED832B /* ESPTouchTask.m */, + FFFA35441C5E01B800ED832B /* ESPTouchResult.m */, + FFFA35471C5E01B800ED832B /* ESPTouchTaskParameter.h */, + FFFA35481C5E01B800ED832B /* ESPTouchTaskParameter.m */, + ); + name = task; + sourceTree = ""; + }; + FFFA34D31C5D210D00ED832B = { + isa = PBXGroup; + children = ( + 0728C71322B39AB8005375E1 /* esptouch */, + 0728C71422B39B46005375E1 /* protocol */, + 0728C71522B39B78005375E1 /* util */, + 0728C71722B39BB6005375E1 /* task */, + 0728C71622B39BA7005375E1 /* udp */, + 07149B0622B3B13B00AD1203 /* ESPAppDelegate.h */, + 07149B0722B3B13B00AD1203 /* ESPAppDelegate.m */, FFFA35131C5DD1E300ED832B /* Smartconfig.h */, FFFA35141C5DD1E300ED832B /* Smartconfig.m */, FFFA34DD1C5D210D00ED832B /* Products */, @@ -191,11 +238,12 @@ FFFA355A1C5E01B800ED832B /* ESPUDPSocketClient.m in Sources */, FFFA35591C5E01B800ED832B /* ESPTouchTaskParameter.m in Sources */, FFFA35581C5E01B800ED832B /* ESPTouchTask.m in Sources */, + 07149B0522B3B12C00AD1203 /* ESPAES.m in Sources */, FFFA35561C5E01B800ED832B /* ESPTouchGenerator.m in Sources */, FF5CEED91E4DE5EC002ADEB9 /* ESP_WifiUtil.m in Sources */, + 07149B0822B3B13B00AD1203 /* ESPAppDelegate.m in Sources */, FFFA354F1C5E01B800ED832B /* ESP_ByteUtil.m in Sources */, FFFA355B1C5E01B800ED832B /* ESPUDPSocketServer.m in Sources */, - FFFA355C1C5E01B800ED832B /* IPAddress.c in Sources */, FFFA35501C5E01B800ED832B /* ESP_CRC8.m in Sources */, FFFA35151C5DD1E300ED832B /* Smartconfig.m in Sources */, FFFA35571C5E01B800ED832B /* ESPTouchResult.m in Sources */, diff --git a/ios/RCTSmartconfig/Smartconfig.m b/ios/RCTSmartconfig/Smartconfig.m index a6f05a1..ad9ee4e 100644 --- a/ios/RCTSmartconfig/Smartconfig.m +++ b/ios/RCTSmartconfig/Smartconfig.m @@ -41,7 +41,7 @@ @interface Smartconfig : NSObject @implementation Smartconfig { - + } @@ -56,12 +56,19 @@ - (instancetype)init @"password": @"password", @"hidden": @NO, @"bssid": @"", - @"timeout": @50000 + @"timeout": @150000, + @"taskCount": @1 }; self._esptouchDelegate = [[EspTouchDelegateImpl alloc]init]; } return self; } + ++ (BOOL)requiresMainQueueSetup +{ + return YES; +} + RCT_EXPORT_METHOD(stop) { [self cancel]; } @@ -101,21 +108,21 @@ - (instancetype)init [ret addObject: respData]; resolved = true; if (![resultInArray isSuc]) - break; + break; } } if(resolved) - resolve(ret); + resolve(ret); else - reject(RCTErrorUnspecified, nil, RCTErrorWithMessage(@"Timoutout or not Found")); + reject(RCTErrorUnspecified, nil, RCTErrorWithMessage(@"Timeoutout or not Found")); }); }); - + } @@ -136,20 +143,38 @@ - (NSArray *) executeForResults { [self cancel]; [self._condition lock]; - NSString *ssid = [self.options valueForKey:@"ssid"]; - NSString *password = [self.options valueForKey:@"password"]; - NSString *bssid = [self.options valueForKey:@"bssid"]; - BOOL hidden = [self.options valueForKey:@"hidden"]; + NSString *base64Ssid = [self.options valueForKey:@"ssid"]; + NSString *base64Password = [self.options valueForKey:@"password"]; + NSString *base64Bssid = [self.options valueForKey:@"bssid"]; + int timeoutMillisecond = [[self.options valueForKey:@"timeout"] intValue]; + int taskCount = [[self.options valueForKey:@"taskCount"] intValue]; + BOOL broadcast = YES; + // BOOL hidden = [self.options valueForKey:@"hidden"]; + + RCTLogInfo(@"ssid %@ pass %@ bssid %@ timeout %d", base64Ssid, base64Password, base64Bssid,timeoutMillisecond); + + // Decode the SSID, BSSID and PASSWORD from B64 to NSString + NSData *nsdataSsid = [[NSData alloc] initWithBase64EncodedString:base64Ssid options:0]; + NSString *ssid = [[NSString alloc] initWithData:nsdataSsid encoding:NSUTF8StringEncoding]; + + NSData *nsdataPassword = [[NSData alloc] initWithBase64EncodedString:base64Password options:0]; + NSString *password = [[NSString alloc] initWithData:nsdataPassword encoding:NSUTF8StringEncoding]; - RCTLogInfo(@"ssid %@ pass %@ bssid %@", ssid, password, bssid); - self._esptouchTask = - [[ESPTouchTask alloc]initWithApSsid:ssid andApBssid:bssid andApPwd:password andIsSsidHiden:hidden]; + NSData *nsdataBssid = [[NSData alloc] initWithBase64EncodedString:base64Bssid options:0]; + NSString *bssid = [[NSString alloc] initWithData:nsdataBssid encoding:NSUTF8StringEncoding]; + + RCTLogInfo(@"ssid %@ pass %@ bssid %@ timeout %d", ssid, password, bssid,timeoutMillisecond); + + self._esptouchTask = [[ESPTouchTask alloc]initWithApSsid:ssid andApBssid:bssid andApPwd:password andTimeoutMillisecond:timeoutMillisecond]; // set delegate [self._esptouchTask setEsptouchDelegate:self._esptouchDelegate]; + [self._esptouchTask setPackageBroadcast:broadcast]; [self._condition unlock]; - NSArray * esptouchResults = [self._esptouchTask executeForResults:1]; + NSArray * esptouchResults = [self._esptouchTask executeForResults:taskCount]; + NSLog(@"ESPViewController executeForResult() result is: %@",esptouchResults); return esptouchResults; } @end + From 60fc2ddb6486bfeae1e852960d0053e570359f4c Mon Sep 17 00:00:00 2001 From: JianYe Date: Sat, 15 Jun 2019 11:02:49 +0800 Subject: [PATCH 2/6] =?UTF-8?q?=E5=8E=BB=E6=8E=89base64=E5=8A=A0=E5=AF=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- android/.project | 17 ++++++++++++++++ .../org.eclipse.buildship.core.prefs | 13 ++++++++++++ .../RCTSmartconfig/RCTSmartconfigModule.java | 19 +++--------------- ios/RCTSmartconfig/Smartconfig.m | 20 ++++--------------- 4 files changed, 37 insertions(+), 32 deletions(-) create mode 100644 android/.project create mode 100644 android/.settings/org.eclipse.buildship.core.prefs diff --git a/android/.project b/android/.project new file mode 100644 index 0000000..3964dd3 --- /dev/null +++ b/android/.project @@ -0,0 +1,17 @@ + + + android + Project android created by Buildship. + + + + + org.eclipse.buildship.core.gradleprojectbuilder + + + + + + org.eclipse.buildship.core.gradleprojectnature + + diff --git a/android/.settings/org.eclipse.buildship.core.prefs b/android/.settings/org.eclipse.buildship.core.prefs new file mode 100644 index 0000000..d65d8f9 --- /dev/null +++ b/android/.settings/org.eclipse.buildship.core.prefs @@ -0,0 +1,13 @@ +arguments= +auto.sync=false +build.scans.enabled=false +connection.gradle.distribution=GRADLE_DISTRIBUTION(VERSION(5.4)) +connection.project.dir= +eclipse.preferences.version=1 +gradle.user.home= +java.home=/Library/Java/JavaVirtualMachines/jdk1.8.0_192.jdk/Contents/Home +jvm.arguments= +offline.mode=false +override.workspace.settings=true +show.console.view=true +show.executions.view=true diff --git a/android/src/main/java/com/tuanpm/RCTSmartconfig/RCTSmartconfigModule.java b/android/src/main/java/com/tuanpm/RCTSmartconfig/RCTSmartconfigModule.java index fbb6ec0..73599bf 100755 --- a/android/src/main/java/com/tuanpm/RCTSmartconfig/RCTSmartconfigModule.java +++ b/android/src/main/java/com/tuanpm/RCTSmartconfig/RCTSmartconfigModule.java @@ -7,7 +7,6 @@ import android.net.Uri; import android.os.Environment; import android.provider.MediaStore; -import android.util.Base64; import android.util.Log; import android.widget.Toast; import android.os.AsyncTask; @@ -103,10 +102,6 @@ public void onFinished(List result) { } } }).execute(ssid, bssid, pass, Integer.toString(taskCount)); - //promise.resolve(encoded); - //promise.reject("Error creating media file."); - // - //Toast.makeText(getReactApplicationContext(), ssid + ":" + pass, 10).show(); } @@ -116,10 +111,6 @@ public interface TaskListener { private class EsptouchAsyncTask extends AsyncTask> { - // - // public interface TaskListener { - // public void onFinished(List result); - // } private final TaskListener taskListener; public EsptouchAsyncTask(TaskListener listener) { @@ -127,7 +118,6 @@ public EsptouchAsyncTask(TaskListener listener) { this.taskListener = listener; } - // 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 @@ -145,12 +135,9 @@ protected List doInBackground(String... params) { Log.d(TAG, "doing task"); int taskCount = -1; synchronized (mLock) { - String apSsidB64 = params[0]; - byte[] apSsid = Base64.decode(apSsidB64, Base64.DEFAULT); - String apBssid64 = params[1]; - byte[] apBssid = Base64.decode(apBssid64, Base64.DEFAULT); - String apPasswordB64 = params[2]; - byte[] apPassword = Base64.decode(apPasswordB64, Base64.DEFAULT); + byte[] apSsid = params[0].getBytes(); + byte[] apBssid = params[1].getBytes(); + byte[] apPassword = params[2].getBytes(); Log.d(TAG, apSsid + " | " + apBssid + " | " + apPassword); String taskCountStr = params[3]; taskCount = Integer.parseInt(taskCountStr); diff --git a/ios/RCTSmartconfig/Smartconfig.m b/ios/RCTSmartconfig/Smartconfig.m index ad9ee4e..fc2af7e 100644 --- a/ios/RCTSmartconfig/Smartconfig.m +++ b/ios/RCTSmartconfig/Smartconfig.m @@ -143,27 +143,15 @@ - (NSArray *) executeForResults { [self cancel]; [self._condition lock]; - NSString *base64Ssid = [self.options valueForKey:@"ssid"]; - NSString *base64Password = [self.options valueForKey:@"password"]; - NSString *base64Bssid = [self.options valueForKey:@"bssid"]; + NSString *ssid = [self.options valueForKey:@"ssid"]; + NSString *password = [self.options valueForKey:@"password"]; + NSString *bssid = [self.options valueForKey:@"bssid"]; int timeoutMillisecond = [[self.options valueForKey:@"timeout"] intValue]; int taskCount = [[self.options valueForKey:@"taskCount"] intValue]; BOOL broadcast = YES; // BOOL hidden = [self.options valueForKey:@"hidden"]; - - RCTLogInfo(@"ssid %@ pass %@ bssid %@ timeout %d", base64Ssid, base64Password, base64Bssid,timeoutMillisecond); - - // Decode the SSID, BSSID and PASSWORD from B64 to NSString - NSData *nsdataSsid = [[NSData alloc] initWithBase64EncodedString:base64Ssid options:0]; - NSString *ssid = [[NSString alloc] initWithData:nsdataSsid encoding:NSUTF8StringEncoding]; - - NSData *nsdataPassword = [[NSData alloc] initWithBase64EncodedString:base64Password options:0]; - NSString *password = [[NSString alloc] initWithData:nsdataPassword encoding:NSUTF8StringEncoding]; - - NSData *nsdataBssid = [[NSData alloc] initWithBase64EncodedString:base64Bssid options:0]; - NSString *bssid = [[NSString alloc] initWithData:nsdataBssid encoding:NSUTF8StringEncoding]; - RCTLogInfo(@"ssid %@ pass %@ bssid %@ timeout %d", ssid, password, bssid,timeoutMillisecond); + RCTLogInfo(@"ssid %@ pass %@ bssid %@ timeout %d", ssid, password, bssid, timeoutMillisecond); self._esptouchTask = [[ESPTouchTask alloc]initWithApSsid:ssid andApBssid:bssid andApPwd:password andTimeoutMillisecond:timeoutMillisecond]; // set delegate From 850791ee7f02f3c046b9754f00fa3a90babfd633 Mon Sep 17 00:00:00 2001 From: JianYe Date: Sat, 15 Jun 2019 11:07:51 +0800 Subject: [PATCH 3/6] =?UTF-8?q?=E5=8E=BB=E6=8E=89base64=E5=8A=A0=E5=AF=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/tuanpm/RCTSmartconfig/RCTSmartconfigModule.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/android/src/main/java/com/tuanpm/RCTSmartconfig/RCTSmartconfigModule.java b/android/src/main/java/com/tuanpm/RCTSmartconfig/RCTSmartconfigModule.java index 73599bf..92b9e3e 100755 --- a/android/src/main/java/com/tuanpm/RCTSmartconfig/RCTSmartconfigModule.java +++ b/android/src/main/java/com/tuanpm/RCTSmartconfig/RCTSmartconfigModule.java @@ -135,9 +135,9 @@ protected List doInBackground(String... params) { Log.d(TAG, "doing task"); int taskCount = -1; synchronized (mLock) { - byte[] apSsid = params[0].getBytes(); - byte[] apBssid = params[1].getBytes(); - byte[] apPassword = params[2].getBytes(); + String apSsid = params[0]; + String apBssid = params[1]; + String apPassword = params[2]; Log.d(TAG, apSsid + " | " + apBssid + " | " + apPassword); String taskCountStr = params[3]; taskCount = Integer.parseInt(taskCountStr); From 095e47fc89679e8920d54136a4786e930e3e6669 Mon Sep 17 00:00:00 2001 From: JianYe Date: Sat, 15 Jun 2019 11:14:33 +0800 Subject: [PATCH 4/6] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=96=87=E6=A1=A3=20?= =?UTF-8?q?=E7=8E=B0=E5=B7=B2=E6=94=AF=E6=8C=81=E8=B6=85=E6=97=B6=E6=97=B6?= =?UTF-8?q?=E9=97=B4=E8=AE=BE=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 62621cf..99ffee1 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,7 @@ Smartconfig.start({ ssid: 'wifi-network-ssid', bssid: 'filter-device', //"" if not need to filter (don't use null) password: 'wifi-password', - timeout: 50000 //now doesn't not effect + timeout: 50000 }).then(function(results){ //Array of device success do smartconfig console.log(results); @@ -100,7 +100,6 @@ Smartconfig.stop(); //interrupt task ## Todo * [ ] Support automatic get current wifi network ssid -* [ ] Set timeout effect * [ ] Support airkiss ## LICENSE From 5bcc1df7482c4050fa986f02884dea98fe01550e Mon Sep 17 00:00:00 2001 From: JianYe Date: Sat, 15 Jun 2019 11:25:28 +0800 Subject: [PATCH 5/6] =?UTF-8?q?=E7=A7=BB=E9=99=A4=E4=B8=80=E4=BA=9B?= =?UTF-8?q?=E7=BC=96=E8=AF=91=E7=8E=AF=E5=A2=83=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- android/.project | 17 --- .../org.eclipse.buildship.core.prefs | 13 -- android/react-native-smartconfig-2.iml | 140 ------------------ 3 files changed, 170 deletions(-) delete mode 100644 android/.project delete mode 100644 android/.settings/org.eclipse.buildship.core.prefs delete mode 100755 android/react-native-smartconfig-2.iml diff --git a/android/.project b/android/.project deleted file mode 100644 index 3964dd3..0000000 --- a/android/.project +++ /dev/null @@ -1,17 +0,0 @@ - - - android - Project android created by Buildship. - - - - - org.eclipse.buildship.core.gradleprojectbuilder - - - - - - org.eclipse.buildship.core.gradleprojectnature - - diff --git a/android/.settings/org.eclipse.buildship.core.prefs b/android/.settings/org.eclipse.buildship.core.prefs deleted file mode 100644 index d65d8f9..0000000 --- a/android/.settings/org.eclipse.buildship.core.prefs +++ /dev/null @@ -1,13 +0,0 @@ -arguments= -auto.sync=false -build.scans.enabled=false -connection.gradle.distribution=GRADLE_DISTRIBUTION(VERSION(5.4)) -connection.project.dir= -eclipse.preferences.version=1 -gradle.user.home= -java.home=/Library/Java/JavaVirtualMachines/jdk1.8.0_192.jdk/Contents/Home -jvm.arguments= -offline.mode=false -override.workspace.settings=true -show.console.view=true -show.executions.view=true diff --git a/android/react-native-smartconfig-2.iml b/android/react-native-smartconfig-2.iml deleted file mode 100755 index 511de04..0000000 --- a/android/react-native-smartconfig-2.iml +++ /dev/null @@ -1,140 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file From 655bcf2d541725ffb769506482c0986d8ec01e23 Mon Sep 17 00:00:00 2001 From: JianYe Date: Sat, 15 Jun 2019 11:30:35 +0800 Subject: [PATCH 6/6] add version description v0.3.7.1 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 99ffee1..90b5671 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ ## Description -[react-native](https://github.com/facebook/react-native) module for [ESP8266 ESPTOUCH Smart config](https://github.com/EspressifApp) +[react-native](https://github.com/facebook/react-native) module for [ESP8266 ESPTOUCH Smart config v0.3.7.1](https://github.com/EspressifApp) ## Featues * Support both IOS and Android