Browse Source

delete useless face_module_2

module-tcpserver-mqtt-t4j-faceSDK
zmt 3 years ago
parent
commit
c9ce572490
  1. 2
      app/build.gradle
  2. 1
      face_module_2/.gitignore
  3. 62
      face_module_2/build.gradle
  4. 0
      face_module_2/consumer-rules.pro
  5. 23
      face_module_2/proguard-rules.pro
  6. 26
      face_module_2/src/androidTest/java/io/dcloud/zmt_module/ExampleInstrumentedTest.java
  7. 5
      face_module_2/src/main/AndroidManifest.xml
  8. 43
      face_module_2/src/main/java/io/dcloud/zmt_module/MyThread.java
  9. 8
      face_module_2/src/main/java/io/dcloud/zmt_module/SocketConfig.java
  10. 53
      face_module_2/src/main/java/io/dcloud/zmt_module/SocketHelper.java
  11. 193
      face_module_2/src/main/java/io/dcloud/zmt_module/TcpServer.java
  12. 189
      face_module_2/src/main/java/io/dcloud/zmt_module/Zmt_AppProxy.java
  13. 49
      face_module_2/src/main/java/io/dcloud/zmt_module/mqtt/MQTTRequest.java
  14. 402
      face_module_2/src/main/java/io/dcloud/zmt_module/mqtt/MQTTSample.java
  15. 92
      face_module_2/src/main/java/io/dcloud/zmt_module/zmtClass.java
  16. 17
      face_module_2/src/test/java/io/dcloud/zmt_module/ExampleUnitTest.java
  17. 2
      settings.gradle

2
app/build.gradle

@ -96,7 +96,7 @@ dependencies {
implementation project(':uniplugin_module_ox')
implementation project(':uniplugin_richalert')
implementation project(':face_module')
// implementation project(':face_module_2')
// implementation project(':new_module')
implementation project(path: ':registerlibrary')
implementation project(path: ':facelibrary')

1
face_module_2/.gitignore

@ -1 +0,0 @@
/build

62
face_module_2/build.gradle

@ -1,62 +0,0 @@
plugins {
id 'com.android.library'
}
android {
compileSdkVersion 29
defaultConfig {
minSdkVersion 16
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles "consumer-rules.pro"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
//aar需要的配置
repositories {
flatDir {
dirs 'libs'
}
}
dependencies {
// implementation 'androidx.appcompat:appcompat:1.1.0'
// implementation 'com.google.android.material:material:1.1.0'
// testImplementation 'junit:junit:4.+'
// androidTestImplementation 'androidx.test.ext:junit:1.1.1'
// androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
//
// //
//// compileOnly 'com.android.support:recyclerview-v7:28.0.0'
//// compileOnly 'com.android.support:support-v4:28.0.0'
//// compileOnly 'com.android.support:appcompat-v7:28.0.0'
// compileOnly 'com.alibaba:fastjson:1.1.46.android'
//
// compileOnly fileTree(include: ['uniapp-v8-release.aar'], dir: '../app/libs')
compileOnly fileTree(dir: 'libs', include: ['*.jar'])
compileOnly 'androidx.recyclerview:recyclerview:1.0.0'
compileOnly 'androidx.legacy:legacy-support-v4:1.0.0'
compileOnly 'androidx.appcompat:appcompat:1.0.0'
compileOnly 'com.alibaba:fastjson:1.1.46.android'
compileOnly fileTree(dir: '../app/libs', include: ['uniapp-v8-release.aar'])
compileOnly 'com.alibaba:fastjson:1.1.46.android'
implementation 'com.tencent.iot.hub:hub-device-android:3.3.5'
}

0
face_module_2/consumer-rules.pro

23
face_module_2/proguard-rules.pro

@ -1,23 +0,0 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
-keep public class * extends io.dcloud.feature.uniapp.common.UniModule{*;}

26
face_module_2/src/androidTest/java/io/dcloud/zmt_module/ExampleInstrumentedTest.java

@ -1,26 +0,0 @@
package io.dcloud.zmt_module;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("io.dcloud.zmt_module.test", appContext.getPackageName());
}
}

5
face_module_2/src/main/AndroidManifest.xml

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.dcloud.zmt_module">
</manifest>

43
face_module_2/src/main/java/io/dcloud/zmt_module/MyThread.java

@ -1,43 +0,0 @@
package io.dcloud.zmt_module;
public class MyThread extends Thread {
String TAG = "zmt---";
public void run(){
System.out.println("MyThread thread running...");
TcpServer server = new TcpServer();
server.initSocket((Integer.parseInt("16666")));
while (true){
String message = server.receiveMessage(SocketConfig.UTF_8);
System.out.println(TAG+"接收消息:"+message);
String send_msg = "收到消息了,你说的对!";
send_msg = SocketHelper.getMessageByReadLine(send_msg);
server.sendMessage(send_msg,SocketConfig.UTF_8);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// while (true){
// String message = server.receiveMessage(SocketConfig.UTF_8);
// System.out.println(TAG+"接收消息:"+message);
//
// String send_msg = "101010";
//
// send_msg = SocketHelper.getMessageByReadLine(send_msg);
// server.sendMessage(send_msg,SocketConfig.UTF_8);
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// }
}
}

8
face_module_2/src/main/java/io/dcloud/zmt_module/SocketConfig.java

@ -1,8 +0,0 @@
package io.dcloud.zmt_module;
public class SocketConfig {
// 设置编码
public static final String UTF_8 = "UTF-8";
public static final String GBK = "GBK";
}

53
face_module_2/src/main/java/io/dcloud/zmt_module/SocketHelper.java

@ -1,53 +0,0 @@
package io.dcloud.zmt_module;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
public class SocketHelper {
public static String getMessageByReadLine(String message) {
message = message + "\n";
return message;
}
public static byte[] toByteArray(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 4];
int n = 0;
while ((n = in.read(buffer)) != -1) {
out.write(buffer, 0, n);
}
return out.toByteArray();
}
public static byte[] toIntByteArray(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[100];
System.out.println("zmt-toIntByteArray--" + buffer[0] + buffer[1] + buffer[2] + buffer[3] + buffer[4] + buffer[5] + " " + Arrays.toString(buffer));
int n = 0;
while ((n = in.read(buffer)) != -1) {
out.write(buffer, 0, n);
}
return out.toByteArray();
}
public static String byte2hex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
String tmp = null;
for (byte b : bytes) {
//将每个字节与0xFF进行与运算然后转化为10进制然后借助于Integer再转化为16进制
tmp = Integer.toHexString(0xFF & b);
if (tmp.length() == 1) {
tmp = "0" + tmp;
}
sb.append(tmp);
}
return sb.toString();
}
}

193
face_module_2/src/main/java/io/dcloud/zmt_module/TcpServer.java

@ -1,193 +0,0 @@
package io.dcloud.zmt_module;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Enumeration;
public class TcpServer {
// 私有变量
private String TAG = "zmt---";
private ServerSocket mServerSocket;
// private DatagramSocket mServerSocket;
private Socket mServer;
private OutputStream mOutStream;
private PrintWriter mPrinter;
private InputStream mInputStream;
private BufferedInputStream mBufferedInputStream;
private InputStreamReader mInputStreamReader;
private BufferedReader mBufferedReader;
/**
*使用本机ip 建立socket server
* @param port 端口号0-65535
*
*/
public void initSocket(int port){
System.out.println(TAG+"initSocket");
try{
if (mServerSocket != null) { mServerSocket.close(); mServerSocket = null; }
if (mServerSocket==null){
mServerSocket = new ServerSocket(port);
mServerSocket.setReuseAddress(true);
// mServerSocket.bind(new InetSocketAddress(port));
InetAddress inetAddress = InetAddress.getLocalHost(); //本机地址
System.out.println(TAG+"tcp server 建立完成:host name"+inetAddress.getHostName()+"\n ---host address:" +
inetAddress.getHostAddress()+" , address:"+inetAddress.getAddress().toString()+" 端口:"+port+ "----"+getIPAddressForNetwork());
}
// if(mServerSocket==null){
// //自己IP收信
//// IPAddress ip = IPAddress.Parse("192.168.1.96");
//
//// String ip = "192.168.1.96";
// InetAddress ip = InetAddress.getByName("192.168.1.96");
//
// mServerSocket = new ServerSocket(port);
// mServerSocket.bind(new IPEndPoint(ip,port));
//
// Socket mServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// m_serverListenSocket.Bind(new IPEndPoint(ip, 10035));
// m_serverListenSocket.Listen(100);
// }
}catch (IOException e){
e.printStackTrace();
}
}
private String getIPAddressForNetwork() throws SocketException {
String address = null;
for(Enumeration<NetworkInterface> enum1 = NetworkInterface.getNetworkInterfaces(); enum1.hasMoreElements();){
NetworkInterface networkInterface = enum1.nextElement();
for(Enumeration<InetAddress> enum2=networkInterface.getInetAddresses(); enum2.hasMoreElements();){
InetAddress inetAddress = enum2.nextElement();
if(!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address){
address = "type: 手机网络\n本机IP: " + inetAddress.getHostAddress().toString();
}
}
}
return address;
}
// 接收消息
public String receiveMessage(String charsetName){
String receiveData=null;
String readLine=null;
// if(mServerSocket==null){
// System.out.println(TAG+"Socket 未启动");
// return null;
// }
System.out.println(TAG+"tcp server receiveMessage ing...");
try{
System.out.println("mServerSocket:"+mServerSocket.toString());
// 获取输入信息
// if(mServerSocket==null){
// System.out.println("mServerSocket 未初始化,无法receiveMessage");
// return null;
// }
mServer = mServerSocket.accept();
mInputStream = mServer.getInputStream();
byte[] data = SocketHelper.toByteArray(mInputStream);
// String _rs = new String(data, "gbk");
// System.out.println(TAG+"二进制读取结果:"+data+" - "+_rs +" - "+SocketHelper.toIntByteArray(mInputStream) + Arrays.toString(data)) ;
System.out.println(TAG+SocketHelper.byte2hex(data));
receiveData = SocketHelper.byte2hex(data);
// 读取输入流
// charsetName = null;
// if(charsetName!=null&&charsetName!=""){
// mInputStreamReader = new InputStreamReader(mInputStream, Charset.forName(charsetName));
// }else{
// mInputStreamReader = new InputStreamReader(mInputStream);
// }
// mBufferedReader = new BufferedReader(mInputStreamReader);
// readLine = mBufferedReader.readLine();
// while (readLine!=null&&readLine!=""){
// System.out.println(TAG+"读取结果:"+readLine);
// break;
// }
System.out.println(TAG+"接收结束,数据:"+receiveData);
} catch (IOException e) {
e.printStackTrace();
}
return receiveData;
}
// 发送消息
public void sendMessage(String message,String charsetName){
if(mServer != null){
System.out.println(TAG+"sendMessage ing...");
try {
mOutStream = mServer.getOutputStream();
mPrinter = new PrintWriter(new OutputStreamWriter(mOutStream,Charset.forName(charsetName)));
mPrinter.println(message);
mPrinter.flush();
System.out.println(TAG+"发送成功 :"+message);
} catch (IOException e) {
System.out.println(TAG+"tcp server sendMessage err :"+message);
e.printStackTrace();
}
}
}
// 关闭连接
public void close(){
try {
if (mPrinter!=null){
mPrinter.close();
}
if (mOutStream!=null){
mOutStream.close();
}
if (mInputStream!=null){
mInputStream.close();
}
if (mInputStreamReader!=null){
mInputStreamReader.close();
}
if (mBufferedReader!=null){
mBufferedReader.close();
}
if (mServer!=null){
mServer.close();
}
System.out.println(TAG+"关闭tcp server <------");
} catch (IOException e) {
e.printStackTrace();
}
}
}

189
face_module_2/src/main/java/io/dcloud/zmt_module/Zmt_AppProxy.java

@ -1,189 +0,0 @@
package io.dcloud.zmt_module;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.tencent.iot.hub.device.android.core.gateway.TXGatewayConnection;
import com.tencent.iot.hub.device.android.core.util.TXLog;
import com.tencent.iot.hub.device.java.core.common.Status;
import com.tencent.iot.hub.device.java.core.mqtt.TXMqttActionCallBack;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import java.util.Arrays;
import io.dcloud.feature.uniapp.UniAppHookProxy;
import io.dcloud.zmt_module.mqtt.MQTTRequest;
import io.dcloud.zmt_module.mqtt.MQTTSample;
public class Zmt_AppProxy implements UniAppHookProxy {
String TAG = "zmt proxy";
private MQTTSample mMQTTSample;
// Default testing parameters
private String mBrokerURL = null; //传入null即使用腾讯云物联网通信默认地址 "${ProductId}.iotcloud.tencentdevices.com:8883" https://cloud.tencent.com/document/product/634/32546
private String mProductID = "";
private String mDevName = "";
private String mDevPSK = "";
private String mSubProductID = ""; // If you wont test gateway, let this to be null
private String mSubDevName = "";
private String mSubDevPsk = "";
private String mTestTopic = ""; // productID/DeviceName/TopicName
// private String mDevCertName = "YOUR_DEVICE_NAME_cert.crt";
// private String mDevKeyName = "YOUR_DEVICE_NAME_private.key";
// private String mProductKey = BuildConfig.PRODUCT_KEY; // Used for dynamic register
private String mDevCert = ""; // Cert String
private String mDevPriv = ""; // Priv String
private final static String BROKER_URL = "broker_url";
private final static String PRODUCT_ID = "product_id";
private final static String DEVICE_NAME = "dev_name";
private final static String DEVICE_PSK = "dev_psk";
private final static String SUB_PRODUCID = "sub_prodid";
private final static String SUB_DEVNAME = "sub_devname";
private final static String TEST_TOPIC = "test_topic";
private final static String DEVICE_CERT = "dev_cert";
private final static String DEVICE_PRIV = "dev_priv";
private final static String PRODUCT_KEY = "product_key";
private final static String SUB_DEVICE_PSK = "sub_dev_psk";
private volatile boolean mIsConnected;
@Override
public void onCreate(Application application) {
Log.e(TAG, "testAsyncFunc--zmt:onCreate");
//当前uni应用进程回调 仅触发一次 多进程不会触发
//可通过UniSDKEngine注册UniModule或者UniComponent
Context mContext = application.getBaseContext();
Object mBrokerURL;
// mMqttConnection = new TXGatewayConnection(mContext, mBrokerURL, mProductID, mDevName, mDevPSK,null,null ,mMqttLogFlag, mMqttLogCallBack, mMqttActionCallBack);
// mMqttConnection.connect(options, mqttRequest);
// SharedPreferences settings = mParent.getSharedPreferences("config", Context.MODE_PRIVATE);
mBrokerURL =null;
mProductID = "BE8N7UZ7OF";
mDevName = "pad20220105";
mDevPSK = "7udrYcfTVThbzdMlLT9fHQ==";
mSubProductID = "";
mSubDevName = "";
mSubDevPsk ="";
mTestTopic = "BE8N7UZ7OF/pad20220105/data";
mDevCert = "";
mDevPriv = "";
// mMQTTSample = new MQTTSample(mContext, new SelfMqttActionCallBack(), null, mProductID, mDevName, mDevPSK,
// mDevCert, mDevPriv, mSubProductID, mSubDevName, mTestTopic, null, null, true, null);
// mMQTTSample.setSubDevPsk(mSubDevPsk);
// mMQTTSample.connect();
// MyThread mt = new MyThread();
// mt.run();
}
@Override
public void onSubProcessCreate(Application application) {
Log.e(TAG, "testAsyncFunc--zmt:onSubProcessCreate");
//其他子进程初始化回调 可用于初始化需要子进程初始化需要的逻辑
}
/**
* 实现TXMqttActionCallBack回调接口
*/
private class SelfMqttActionCallBack extends TXMqttActionCallBack {
@Override
public void onConnectCompleted(Status status, boolean reconnect, Object userContext, String msg, Throwable cause) {
String userContextInfo = "";
if (userContext instanceof MQTTRequest) {
userContextInfo = userContext.toString();
}
String logInfo = String.format("我在uni里链接成功了!onConnectCompleted, status[%s], reconnect[%b], userContext[%s], msg[%s]",
status.name(), reconnect, userContextInfo, msg);
// mParent.printLogInfo(TAG, logInfo, mLogInfoText, TXLog.LEVEL_INFO);
System.out.println(TAG+logInfo);
mIsConnected = true;
}
@Override
public void onConnectionLost(Throwable cause) {
String logInfo = String.format("onConnectionLost, cause[%s]", cause.toString());
// mParent.printLogInfo(TAG, logInfo, mLogInfoText, TXLog.LEVEL_INFO);
System.out.println(TAG+logInfo);
}
@Override
public void onDisconnectCompleted(Status status, Object userContext, String msg, Throwable cause) {
String userContextInfo = "";
if (userContext instanceof MQTTRequest) {
userContextInfo = userContext.toString();
}
String logInfo = String.format("onDisconnectCompleted, status[%s], userContext[%s], msg[%s]", status.name(), userContextInfo, msg);
// mParent.printLogInfo(TAG, logInfo, mLogInfoText, TXLog.LEVEL_INFO);
System.out.println(TAG+logInfo);
mIsConnected = false;
}
@Override
public void onPublishCompleted(Status status, IMqttToken token, Object userContext, String errMsg, Throwable cause) {
String userContextInfo = "";
if (userContext instanceof MQTTRequest) {
userContextInfo = userContext.toString();
}
String logInfo = String.format("onPublishCompleted, status[%s], topics[%s], userContext[%s], errMsg[%s]",
status.name(), Arrays.toString(token.getTopics()), userContextInfo, errMsg);
// mParent.printLogInfo(TAG, logInfo, mLogInfoText);
System.out.println(TAG+logInfo);
}
@Override
public void onSubscribeCompleted(Status status, IMqttToken asyncActionToken, Object userContext, String errMsg, Throwable cause) {
String userContextInfo = "";
if (userContext instanceof MQTTRequest) {
userContextInfo = userContext.toString();
}
String logInfo = String.format("onSubscribeCompleted, status[%s], topics[%s], userContext[%s], errMsg[%s]",
status.name(), Arrays.toString(asyncActionToken.getTopics()), userContextInfo, errMsg);
if (Status.ERROR == status) {
// mParent.printLogInfo(TAG, logInfo, mLogInfoText, TXLog.LEVEL_ERROR);
System.out.println(TAG+logInfo);
} else {
// mParent.printLogInfo(TAG, logInfo, mLogInfoText);
System.out.println(TAG+logInfo);
}
}
@Override
public void onUnSubscribeCompleted(Status status, IMqttToken asyncActionToken, Object userContext, String errMsg, Throwable cause) {
String userContextInfo = "";
if (userContext instanceof MQTTRequest) {
userContextInfo = userContext.toString();
}
String logInfo = String.format("onUnSubscribeCompleted, status[%s], topics[%s], userContext[%s], errMsg[%s]",
status.name(), Arrays.toString(asyncActionToken.getTopics()), userContextInfo, errMsg);
// mParent.printLogInfo(TAG, logInfo, mLogInfoText);
System.out.println(TAG+logInfo);
}
@Override
public void onMessageReceived(final String topic, final MqttMessage message) {
String logInfo = String.format("receive command, topic[%s], message[%s]", topic, message.toString());
// mParent.printLogInfo(TAG, logInfo, mLogInfoText);
System.out.println(TAG+logInfo);
}
}
}

49
face_module_2/src/main/java/io/dcloud/zmt_module/mqtt/MQTTRequest.java

@ -1,49 +0,0 @@
package io.dcloud.zmt_module.mqtt;
public class MQTTRequest {
private static final String TAG = MQTTRequest.class.getSimpleName();
/**
* 请求类型
*/
private String requestType = "";
/**
* 请求ID
*/
private int requestId = 0;
public MQTTRequest() {
}
public MQTTRequest(String requestType, int requestId) {
this.requestType = requestType;
this.requestId = requestId;
}
public String getRequestType() {
return requestType;
}
public void setRequestType(String requestType) {
this.requestType = requestType;
}
public int getRequestId() {
return requestId;
}
public void setRequestId(int requestId) {
this.requestId = requestId;
}
@Override
public String toString() {
return "MQTTRequest{" +
"requestType='" + requestType + '\'' +
", requestId=" + requestId +
'}';
}
}

402
face_module_2/src/main/java/io/dcloud/zmt_module/mqtt/MQTTSample.java

@ -1,402 +0,0 @@
package io.dcloud.zmt_module.mqtt;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import com.tencent.iot.hub.device.android.core.gateway.TXGatewayConnection;
import com.tencent.iot.hub.device.android.core.util.AsymcSslUtils;
import com.tencent.iot.hub.device.android.core.util.TXLog;
import com.tencent.iot.hub.device.java.core.log.TXMqttLogCallBack;
import com.tencent.iot.hub.device.java.core.mqtt.TXMqttActionCallBack;
import com.tencent.iot.hub.device.java.core.mqtt.TXMqttConstants;
import com.tencent.iot.hub.device.java.core.mqtt.TXOTACallBack;
import com.tencent.iot.hub.device.java.core.mqtt.TXOTAConstansts;
import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
public class MQTTSample {
private static final String TAG = "TXMQTT";
// Default Value, should be changed in testing
private String mBrokerURL = null; //传入null即使用腾讯云物联网通信默认地址 "${ProductId}.iotcloud.tencentdevices.com:8883" https://cloud.tencent.com/document/product/634/32546
private String mProductID = "PRODUCT-ID";
private String mDevName = "DEVICE-NAME";
private String mDevPSK = "DEVICE-SECRET";
private String mDevCertName = "DEVICE_CERT-NAME ";
private String mDevKeyName = "DEVICE_KEY-NAME ";
private String mSubProductID = "SUBDEV_PRODUCT-ID";
private String mSubDevName = "SUBDEV_DEV-NAME";
private String mSubDevPsk = "SUBDEV_DEVICE-SECRET";
private String mTestTopic = "TEST_TOPIC_WITH_SUB_PUB";
private String mDevCert;
private String mDevPriv;
private boolean mMqttLogFlag;
private TXMqttLogCallBack mMqttLogCallBack;
private Context mContext;
private String path2Store = "";
private TXMqttActionCallBack mMqttActionCallBack;
/**
* MQTT连接实例
*/
private TXGatewayConnection mMqttConnection;
/**
* 请求ID
*/
private static AtomicInteger requestID = new AtomicInteger(0);
public MQTTSample(Context context, TXMqttLogCallBack logCallBack, TXMqttActionCallBack callBack) {
mContext = context;
mMqttActionCallBack = callBack;
}
public MQTTSample(Context context, TXMqttActionCallBack callBack, String brokerURL, String productId,
String devName, String devPSK, String subProductID, String subDevName, String testTopic, String devCertName, String devKeyName,
Boolean mqttLogFlag, TXMqttLogCallBack logCallBack) {
mBrokerURL = brokerURL;
mProductID = productId;
mDevName = devName;
mDevPSK = devPSK;
mSubProductID = subProductID;
mSubDevName = subDevName;
mTestTopic = testTopic;
mDevCertName = devCertName;
mDevKeyName = devKeyName;
mMqttLogFlag = mqttLogFlag;
mMqttLogCallBack = logCallBack;
mContext = context;
mMqttActionCallBack = callBack;
}
public MQTTSample(Context context, TXMqttActionCallBack callBack, String brokerURL, String productId,
String devName, String devPsk, String devCert, String devPriv, String subProductID, String subDevName, String testTopic, String devCertName, String devKeyName,
Boolean mqttLogFlag, TXMqttLogCallBack logCallBack) {
mBrokerURL = brokerURL;
mProductID = productId;
mDevName = devName;
mDevPSK = devPsk;
mDevCert = devCert;
mDevPriv = devPriv;
mSubProductID = subProductID;
mSubDevName = subDevName;
mTestTopic = testTopic;
mDevCertName = devCertName;
mDevKeyName = devKeyName;
mMqttLogFlag = mqttLogFlag;
mMqttLogCallBack = logCallBack;
mContext = context;
mMqttActionCallBack = callBack;
path2Store = mContext.getCacheDir().getAbsolutePath();
}
public MQTTSample(Context context, TXMqttActionCallBack callBack, String brokerURL, String productId,
String devName, String devPsk, String devCert, String devPriv, String subProductID, String subDevName, String subDevPsk, String testTopic, String devCertName, String devKeyName,
Boolean mqttLogFlag, TXMqttLogCallBack logCallBack) {
this(context, callBack, brokerURL, productId, devName, devPsk, devCert, devPriv, subProductID, subDevName, testTopic, devCertName, devKeyName, mqttLogFlag, logCallBack);
mSubDevPsk = subDevPsk;
}
public void setSubDevPsk(String val) {
mSubDevPsk = val;
}
public MQTTSample(Context context, TXMqttActionCallBack callBack, String brokerURL, String productId,
String devName, String devPSK, String subProductID, String subDevName, String testTopic) {
mBrokerURL = brokerURL;
mProductID = productId;
mDevName = devName;
mDevPSK = devPSK;
mSubProductID = subProductID;
mSubDevName = subDevName;
mTestTopic = testTopic;
mContext = context;
mMqttActionCallBack = callBack;
}
private TXOTACallBack oTACallBack = new TXOTACallBack() {
@Override
public void onReportFirmwareVersion(int resultCode, String version, String resultMsg) {
}
@Override
public boolean onLastestFirmwareReady(String url, String md5, String version) {
System.out.println("onLastestFirmwareReady url=" + url + " version " + version);
mMqttConnection.gatewayDownSubdevApp(url, path2Store + "/" + md5, md5, version);
return true; // false 自动触发下载升级文件 true 需要手动触发下载升级文件
}
@Override
public void onDownloadProgress(int percent, String version) {
mMqttConnection.gatewaySubdevReportProgress(percent, version);
}
@Override
public void onDownloadCompleted(String outputFile, String version) {
mMqttConnection.gatewaySubdevReportStart(version);
mMqttConnection.gatewaySubdevReportSuccess(version);
}
@Override
public void onDownloadFailure(int errCode, String version) {
mMqttConnection.gatewaySubdevReportFail(errCode, "", version);
}
};
/**
* 建立MQTT连接
*/
public void connect() {
mMqttConnection = new TXGatewayConnection(mContext, mBrokerURL, mProductID, mDevName, mDevPSK,null,null ,mMqttLogFlag, mMqttLogCallBack, mMqttActionCallBack);
mMqttConnection.setSubDevName(mSubDevName);
mMqttConnection.setSubDevProductKey(mSubDevPsk);
mMqttConnection.setSubProductID(mSubProductID);
MqttConnectOptions options = new MqttConnectOptions();
options.setConnectionTimeout(8);
options.setKeepAliveInterval(240);
options.setAutomaticReconnect(true);
if (mDevPriv != null && mDevCert != null && mDevPriv.length() != 0 && mDevCert.length() != 0) {
TXLog.i(TAG, "Using cert stream " + mDevPriv + " " + mDevCert);
options.setSocketFactory(AsymcSslUtils.getSocketFactoryByStream(new ByteArrayInputStream(mDevCert.getBytes()), new ByteArrayInputStream(mDevPriv.getBytes())));
} else if (mDevPSK != null && mDevPSK.length() != 0){
TXLog.i(TAG, "Using PSK");
// options.setSocketFactory(AsymcSslUtils.getSocketFactory()); 如果您使用的是3.3.0及以下版本的 hub-device-android sdk由于密钥认证默认配置的ssl://的url请添加此句setSocketFactory配置
} else {
TXLog.i(TAG, "Using cert assets file");
options.setSocketFactory(AsymcSslUtils.getSocketFactoryByAssetsFile(mContext, mDevCertName, mDevKeyName));
}
MQTTRequest mqttRequest = new MQTTRequest("connect", requestID.getAndIncrement());
mMqttConnection.connect(options, mqttRequest);
DisconnectedBufferOptions bufferOptions = new DisconnectedBufferOptions();
bufferOptions.setBufferEnabled(true);
bufferOptions.setBufferSize(1024);
bufferOptions.setDeleteOldestMessages(true);
mMqttConnection.setBufferOpts(bufferOptions);
}
/**
* 断开MQTT连接
*/
public void disconnect() {
MQTTRequest mqttRequest = new MQTTRequest("disconnect", requestID.getAndIncrement());
mMqttConnection.disConnect(mqttRequest);
}
public void setSubdevOnline() {
// set subdev online
mMqttConnection.gatewaySubdevOnline(mSubProductID, mSubDevName);
}
public void setSubDevOffline() {
mMqttConnection.gatewaySubdevOffline(mSubProductID, mSubDevName);
}
public void setSubDevBinded() {
mMqttConnection.gatewayBindSubdev(mSubProductID, mSubDevName, mSubDevPsk);
}
public void setSubDevUnbinded() {
mMqttConnection.gatewayUnbindSubdev(mSubProductID, mSubDevName);
}
public void checkSubdevRelation() {
mMqttConnection.getGatewaySubdevRealtion();
}
public void getRemoteConfig() {
mMqttConnection.getRemoteConfig();
}
public void concernRemoteConfig() {
mMqttConnection.concernConfig();
}
public void reportSubDevVersion(String version) {
mMqttConnection.gatewaySubdevReportVer(version);
}
public void subscribeNTPTopic() {
// QOS等级
int qos = TXMqttConstants.QOS1;
// 用户上下文请求实例
MQTTRequest mqttRequest = new MQTTRequest("subscribeNTPTopic", requestID.getAndIncrement());
mMqttConnection.subscribeNTPTopic(qos, mqttRequest);
}
public void getNTPService() {
mMqttConnection.getNTPService();
}
public void initOTA() {
TXLog.e(TAG, "path2Store " + path2Store);
mMqttConnection.initOTA(path2Store, oTACallBack);
}
/**
* 订阅广播主题
*/
public void subscribeBroadCastTopic() {
// 用户上下文请求实例
MQTTRequest mqttRequest = new MQTTRequest("subscribeTopic", requestID.getAndIncrement());
// 订阅广播主题
mMqttConnection.subscribeBroadcastTopic(TXMqttConstants.QOS1, mqttRequest);
}
/**
* 订阅主题
*
*/
public void subscribeTopic() {
// 主题
String topic = mTestTopic;
// QOS等级
int qos = TXMqttConstants.QOS1;
// 用户上下文请求实例
MQTTRequest mqttRequest = new MQTTRequest("subscribeTopic", requestID.getAndIncrement());
Log.d(TAG, "sub topic is " + topic);
// 订阅主题
mMqttConnection.subscribe(topic, qos, mqttRequest);
}
/**
* 取消订阅主题
*
*/
public void unSubscribeTopic() {
// 主题
String topic = mTestTopic;
// 用户上下文请求实例
MQTTRequest mqttRequest = new MQTTRequest("unSubscribeTopic", requestID.getAndIncrement());
Log.d(TAG, "Start to unSubscribe" + topic);
// 取消订阅主题
mMqttConnection.unSubscribe(topic, mqttRequest);
}
/**
* 发布主题
*/
public void publishTopic(String topicName, Map<String, String> data) {
// 主题
String topic = mTestTopic;
// MQTT消息
MqttMessage message = new MqttMessage();
JSONObject jsonObject = new JSONObject();
try {
for (Map.Entry<String, String> entrys : data.entrySet()) {
jsonObject.put(entrys.getKey(), entrys.getValue());
}
} catch (JSONException e) {
TXLog.e(TAG, e, "pack json data failed!");
}
message.setQos(TXMqttConstants.QOS1);
message.setPayload(jsonObject.toString().getBytes());
// 用户上下文请求实例
MQTTRequest mqttRequest = new MQTTRequest("publishTopic", requestID.getAndIncrement());
Log.d(TAG, "pub topic " + topic + message);
// 发布主题
mMqttConnection.publish(topic, message, mqttRequest);
}
/**
* 订阅RRPC主题
*
*/
public void subscribeRRPCTopic() {
// 用户上下文请求实例
MQTTRequest mqttRequest = new MQTTRequest("subscribeTopic", requestID.getAndIncrement());
// 订阅主题
mMqttConnection.subscribeRRPCTopic(TXMqttConstants.QOS0, mqttRequest);
}
/**
* 生成一条日志
* @param logLevel 日志级别
* 错误TXMqttLogConstants.LEVEL_ERROR
* 警告TXMqttLogConstants.LEVEL_WARN
* 通知TXMqttLogConstants.LEVEL_INFO
* 调试TXMqttLogConstants.LEVEL_DEBUG
* @param tag
* @param format
* @param obj
*/
public void mLog(int logLevel, final String tag,final String format, final Object... obj) {
if (mMqttLogFlag)
mMqttConnection.mLog(logLevel, tag, format, obj);
}
/**
* 发起一次日志上传
*/
public void uploadLog() {
mMqttConnection.uploadLog();
}
public void checkFirmware() {
mMqttConnection.initOTA(Environment.getExternalStorageDirectory().getAbsolutePath(), new TXOTACallBack() {
@Override
public void onReportFirmwareVersion(int resultCode, String version, String resultMsg) {
TXLog.e(TAG, "onReportFirmwareVersion:" + resultCode + ", version:" + version + ", resultMsg:" + resultMsg);
}
@Override
public boolean onLastestFirmwareReady(String url, String md5, String version) {
TXLog.e(TAG, "MQTTSample onLastestFirmwareReady");
return false;
}
@Override
public void onDownloadProgress(int percent, String version) {
TXLog.e(TAG, "onDownloadProgress:" + percent);
}
@Override
public void onDownloadCompleted(String outputFile, String version) {
TXLog.e(TAG, "onDownloadCompleted:" + outputFile + ", version:" + version);
mMqttConnection.reportOTAState(TXOTAConstansts.ReportState.DONE, 0, "OK", version);
}
@Override
public void onDownloadFailure(int errCode, String version) {
TXLog.e(TAG, "onDownloadFailure:" + errCode);
mMqttConnection.reportOTAState(TXOTAConstansts.ReportState.FAIL, errCode, "FAIL", version);
}
});
mMqttConnection.reportCurrentFirmwareVersion("0.0.1");
}
}

92
face_module_2/src/main/java/io/dcloud/zmt_module/zmtClass.java

@ -1,92 +0,0 @@
package io.dcloud.zmt_module;
import com.alibaba.fastjson.JSONObject;
import com.tencent.iot.hub.device.android.core.gateway.TXGatewayConnection;
import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.common.UniModule;
import android.util.Log;
public class zmtClass extends UniModule {
String TAG = "zmt--22222-";
//run ui thread
@UniJSMethod(uiThread = true)
public void testAsyncFunc(JSONObject options, final UniJSCallback callback) {
Log.e(TAG, "testAsync22222Func--zmt:"+options);
//启动线程
// MyThread mt = new MyThread();
// mt.run();
if(callback != null) {
JSONObject data = new JSONObject();
data.put("code", "2222已开启服务,等待接收数据");
// callback.invoke(data);
}
// Android 4.0 之后不能在主线程中请求HTTP请求
new Thread(new Runnable(){
@Override
public void run() {
System.out.println("MyThread thread running...");
TcpServer server = new TcpServer();
server.initSocket((Integer.parseInt("16666")));
while (true){
String message = server.receiveMessage(SocketConfig.UTF_8);
System.out.println(TAG+"接收消息:"+message);
JSONObject data = new JSONObject();
data.put("code", message);
// callback.invoke(data);
callback.invokeAndKeepAlive(data);
String send_msg = "1111111111111";
send_msg = SocketHelper.getMessageByReadLine(send_msg);
server.sendMessage(send_msg,SocketConfig.UTF_8);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
// @UniJSMethod(uiThread = true)
// public void testAsyncFunc(JSONObject options, UniJSCallback callback) {
// Log.e(TAG, "testAsyncFunc--zmt:"+options);
//
// if(callback != null) {
// JSONObject data = new JSONObject();
// data.put("code", "success-zmt async");
// callback.invoke(data);
// }
// }
//run JS thread
@UniJSMethod(uiThread = false)
public JSONObject testSyncFunc(){
Log.e(TAG, "testSyncFunc--zmt2");
JSONObject data = new JSONObject();
data.put("code", "success-zmt sync");
return data;
}
}

17
face_module_2/src/test/java/io/dcloud/zmt_module/ExampleUnitTest.java

@ -1,17 +0,0 @@
package io.dcloud.zmt_module;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
}

2
settings.gradle

@ -1,4 +1,4 @@
//include ':face_module_2'
//include ':new_module'
include ':face_module'
include ':zmt_module'
include ':ox_module'

Loading…
Cancel
Save