whyclj
2019-07-24 c9f8b9e09489e547734246140b4fd3635100fbb6
测试java和js通信
8个文件已修改
1个文件已删除
5个文件已添加
10617 ■■■■■ 已修改文件
.idea/misc.xml 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/build.gradle 3 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/libs/gson-2.2.4.jar 补丁 | 查看 | 原始文档 | blame | 历史
app/src/main/AndroidManifest.xml 18 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/src/main/assets/apps/HelloH5/www/index.html 6 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/src/main/assets/apps/HelloH5/www/js/jquery-1.8.3.js 9472 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/src/main/assets/apps/HelloH5/www/pages/home.html 12 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/src/main/assets/apps/HelloH5/www/pages/test.html 82 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/src/main/java/com/activitys/Index_activity.java 179 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/src/main/java/com/comm/MyWebSocketTestThread.java 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/src/main/java/com/comm/ServiceModel.java 83 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/src/main/java/com/fbo2206/MySocketClientThread.java 742 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/src/main/java/com/fbs9100/FBS_ComBase.java 3 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/src/main/res/layout/index_layout.xml 13 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
.idea/misc.xml
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" project-jdk-name="JDK" project-jdk-type="JavaSDK">
  <component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" project-jdk-name="JDK" project-jdk-type="JavaSDK">
    <output url="file://$PROJECT_DIR$/build/classes" />
  </component>
  <component name="ProjectType">
app/build.gradle
@@ -31,7 +31,8 @@
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation(name:'lib.5plus.base-release', ext: 'aar')
    implementation files('libs/gson-2.2.4.jar')
    implementation 'com.google.code.gson:gson:2.8.5'
    //implementation files('libs/gson-2.2.4.jar')
}
app/libs/gson-2.2.4.jar
Binary files differ
app/src/main/AndroidManifest.xml
@@ -1,32 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.webapp">
    <!-- Barcode(二维码)  begin -->
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.FLASHLIGHT" />
    <!-- Barcode(二维码)  end -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:name="io.dcloud.application.DCloudApplication"
        android:allowClearUserData="true"
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:largeHeap="true"
        >
        android:largeHeap="true">
        <!--android:name="io.dcloud.PandoraEntry"-->
        <activity
            android:name="io.dcloud.PandoraEntry"
            android:name="com.activitys.Index_activity"
            android:configChanges="orientation|keyboardHidden|keyboard|navigation"
            android:hardwareAccelerated="true"
            android:label="@string/app_name"
            android:launchMode="singleTask"
            android:hardwareAccelerated="true"
            android:theme="@style/TranslucentTheme"
            android:screenOrientation="user"
            android:windowSoftInputMode="adjustResize" >
            android:theme="@style/TranslucentTheme"
            android:windowSoftInputMode="adjustResize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
app/src/main/assets/apps/HelloH5/www/index.html
@@ -32,12 +32,6 @@
            }]
        });
        mui.plusReady(function() {
            var w=new Worker("js/coment/SocketClient.js");
            w.onmessage = function (event) {
                console.info(event+"###################################################");
            };
        });
    </script>
app/src/main/assets/apps/HelloH5/www/js/jquery-1.8.3.js
New file
Diff too large
app/src/main/assets/apps/HelloH5/www/pages/home.html
@@ -30,13 +30,13 @@
            <div style="height: 30px;"></div>
            <div class="mui-row" id="menuList">
                <div class="mui-col-xs-4 mui-col-sm-4">
                    <a href="" class="grid-9-content">
                    <a href="javascript:void(0);" class="grid-9-content">
                        <img src="../images/ele-charge.gif" />
                        <div class="mui-media-body color-white">充电测试</div>
                    </a>
                </div>
                <div class="mui-col-xs-4 mui-col-sm-4">
                    <a href="" class="grid-9-content">
                    <a href="javascript:void(0);" class="grid-9-content">
                        <img src="../images/ele-discharge.gif">
                        <div class="mui-media-body color-white">放电测试</div>
                    </a>
@@ -54,13 +54,13 @@
                    </a>
                </div>
                <div class="mui-col-xs-4 mui-col-sm-4">
                    <a href="" class="grid-9-content">
                    <a href="javascript:void(0);" class="grid-9-content">
                        <img src="../images/report-icon.gif">
                        <div class="mui-media-body color-white">报表管理</div>
                    </a>
                </div>
                <div class="mui-col-xs-4 mui-col-sm-4">
                    <a href="" class="grid-9-content">
                    <a href="../pages/test.html" class="grid-9-content">
                        <img src="../images/sys-icon.gif">
                        <div class="mui-media-body color-white">系统设置</div>
                    </a>
@@ -71,12 +71,13 @@
    <script src="../js/mui.min.js"></script>
    <script src="../iconfont/iconfont.js"></script>
    <script src="../js/common.js"></script>
    <script src="../libs/socket.io/socket.io.js"></script>
    <script>
        mui.init();
        mui.plusReady(function() {
            // 点击显示扫描二维码
            mui(".mui-bar-nav").on('tap', '.scan-scan',function() {
                //打开新窗口
                mui.openWindow('../pages/barcode.html', 'pages/barcode.html', {
                    styles: {
@@ -95,7 +96,6 @@
            });
            console.log("*********************************************************");
            //console.log(io);
            console.log("*********************************************************");
        });
app/src/main/assets/apps/HelloH5/www/pages/test.html
New file
@@ -0,0 +1,82 @@
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>home</title>
    <link href="../css/mui.min.css" rel="stylesheet" />
    <link href="../css/common.css" rel="stylesheet">
    <link href="../libs/iconfont/iconfont.css" rel="stylesheet">
    <style>
        .icon {
            width: 1em;
            height: 1em;
            vertical-align: -0.15em;
            fill: currentColor;
            overflow: hidden;
        }
    </style>
</head>
<body class="bg-info">
    <header class="mui-bar mui-bar-nav bg-primary-dark">
        <h1 class="mui-title color-white">蓄电池智能分析终端</h1>
        <a class="scan-scan mui-icon iconfont icon-saoyisaoerweimasaomasaomiao mui-pull-right color-white"></a>
    </header>
    <!-- 主页面内容容器 -->
    <div class="mui-content">
        <span id="number">1132</span>
        <br>
        <input id = "username" >    <button onclick="myOnclick()">提交</button><button onclick="test()">获取用户名</button>
    </div>
    <script src="../js/mui.min.js"></script>
    <script src="../js/common.js"></script>
    <script src="../js/jquery-1.8.3.js"></script>
</body>
</html>
    <script>
        mui.init();
        mui.plusReady(function() {
        });
        var i = 0;
        setInterval(function(){
            $('#number').text(++i)
        },100);
        //点击事件
        function myOnclick(){
            var username = document.getElementById('username').value;
            if(username != null && username.length>0){
                window.model.setUsername(username);
            }
        }
        //获取用户名
        function test(){
            var temp = {
                cmd:0x02,
                msg:"127.0.0.1"
            };
            window.JavaScriptInterface.receiveMessageFromJavaScript(JSON.stringify(temp));
        }
        function showInfoFromJava(json){
            console.info("***********************************************************************");
            //console.info(window.user.getUsername());
            console.info(json);
            console.info("***********************************************************************");
        }
    </script>
app/src/main/java/com/activitys/Index_activity.java
New file
@@ -0,0 +1,179 @@
package com.activitys;
import androidx.annotation.NonNull;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import com.comm.ServiceModel;
import com.example.webapp.R;
import com.fbo2206.FBO_ParamDischarge;
import com.fbo2206.MySocketClientThread;
import com.fbs9100.FBS_ComBase;
import com.google.gson.Gson;
import io.dcloud.c.h;
public class Index_activity extends Activity {
    private final static  String TAG = "Index_activity";
    private ServiceModel model;
    private WebView webView;
    private Handler handler;
    private MyJavaScriptInterface myJavaScriptInterface;
    private MySocketClientThread socketClientThread = null;
    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.index_layout);
        //方式1:直接在在Activity中生成
        webView = (WebView)findViewById(R.id.my_webview);
        //handler = new Handler();
        //设置支持JavaScript语言,让WebView支持javascript的动作
        webView.getSettings().setJavaScriptEnabled(true);
        WebSettings webSettings = webView.getSettings();
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setDefaultTextEncodingName("utf-8");
        //交互对象的添加,传入对象在html5界面的javascript中获取,该对象用于两者之间的交互。question,给JavaScript添加一个与之交互的接口,传入一个对象和该对象的名字,在html5端根据这个名字得到对象
        //提供一个供h5交互的对象,并给对象标记个名字供js识别
        //webView.addJavascriptInterface( model = new ServiceModel(), "model");
        //webView.addJavascriptInterface( mUser = new User(), "user");
        webView.addJavascriptInterface( myJavaScriptInterface = new MyJavaScriptInterface(), "JavaScriptInterface");
        //自定义实现alert
        webView.setWebChromeClient(new MyWebChromClient());
        //要加载的页面
        webView.loadUrl("file:///android_asset/apps/HelloH5/www/index.html");
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view,String  url) {
                view.loadUrl(url);
                return true;
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        });
        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
            if(webView != null){
                ServiceModel model = (ServiceModel)msg.obj;
                Log.e(TAG, "handleMessage: "+model+"%%%%%%%%%%%%" );
                myJavaScriptInterface.sendMessageToJavaScript(model);
            }
            }
        };
        socketClientThread = new MySocketClientThread();
        socketClientThread.start();
    }
    @Override
    protected void onDestroy() {
        if (webView != null) {
            webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            webView.clearHistory();
            ((ViewGroup) webView.getParent()).removeView(webView);
            webView.destroy();
            webView = null;
        }
        super.onDestroy();
    }
    class MyWebViewClient extends WebViewClient {
        //不重新打开系统的浏览器加载网页
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }
    private class MyWebChromClient extends WebChromeClient{
        //捕获html5 js中的alert事件, 将alert事件转换为Toast形式显示,但是不道为啥我的能toast,但是toast之后输入框的焦点就没有了,不能再输入第二次了,我用的是魅族手机
        @Override
        public boolean onJsAlert(WebView view, String url, String message,
                        JsResult result) {
            Toast.makeText(Index_activity.this, message, Toast.LENGTH_SHORT).show();
            Log.i("TAG", message);
            return true;
        }
    }
    class MyJavaScriptInterface{
        private Gson gson ;
        //将接收到的数据发送给前台JS
        public void sendMessageToJavaScript(ServiceModel model){
            gson = new Gson();
            String json = gson.toJson(model);
            webView.loadUrl("javascript:showInfoFromJava('" + json + "')");
        }
        @JavascriptInterface
        //接收前台JS发送的数据
        public void receiveMessageFromJavaScript(String json){
            Log.e(TAG, "receiveMessageFromJavaScript: $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"+json);
            gson = new Gson();
            model = gson.fromJson(json,ServiceModel.class);
            Log.e(TAG, "receiveMessageFromJavaScript: "+model);
            Log.e(TAG, "receiveMessageFromJavaScript: "+"##############################################################" );
            Object obj = null;
            if(FBS_ComBase.CMD_SETDEVICEIP == model.cmd){
                //设置设备的ip地址
                MySocketClientThread.server_ip = model.msg;
                model.cmd = FBS_ComBase.CMD_STARTCNNECT;                //开始通信
            }else if(FBS_ComBase.CMD_SetDischargeParm == model.cmd){
                FBO_ParamDischarge param = gson.fromJson(model.data.toString(),FBO_ParamDischarge.class);
                obj = param;
            }
            sendMessageToSocketClient(handler,model.cmd,obj);
        }
    }
    private boolean sendMessageToSocketClient(Handler handler, int cmd, Object FBS_data)
    {
        ServiceModel model = new ServiceModel();
        model.handler = handler;
        model.msg = "Request FBSdata from BattChargeParamACT";
        model.cmd = cmd;
        model.data = FBS_data;
        Message childMsg = socketClientThread.mHandler.obtainMessage();
        childMsg.obj = model;
        return (socketClientThread.mHandler.sendMessage(childMsg));
    }
}
app/src/main/java/com/comm/MyWebSocketTestThread.java
@@ -208,8 +208,6 @@
    */
    /**
     *     向指定的socket通道发送数据,以及接收数据
     * @return
app/src/main/java/com/comm/ServiceModel.java
@@ -1,11 +1,21 @@
package com.comm;
import android.os.Handler;
import android.webkit.JavascriptInterface;
import com.fbo2206.FBO_ParamDischarge;
import com.fbs9100.FBS_ComBase;
import com.google.gson.Gson;
import java.nio.ByteBuffer;
public class ServiceModel
{
    public int code;
    public int cmd;
    public String msg;
    public Object data;
    public Handler handler;
    public ServiceModel()
    {
@@ -13,5 +23,78 @@
        int code = 0;
        int cmd = 0;
        Object data = null;
        handler = null;
    }
    public ByteBuffer createByteBuffer(){
        ByteBuffer byteBuffer = ByteBuffer.allocate(0);
        if(code == FBS_ComBase.CMD_SetDischargeParm){
            Gson gson = new Gson();
            FBO_ParamDischarge param = gson.fromJson(data.toString(), FBO_ParamDischarge.class);
            byteBuffer =  param.getByteBuffer();
        }
        return byteBuffer;
    }
    @JavascriptInterface
    public void setServiceModel(int cmd,Object data){
        this.cmd = cmd;
        this.data = data;
    }
    @JavascriptInterface
    public ServiceModel getServiceModel(){
        return this;
    }
    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }
    public int getCmd() {
        return cmd;
    }
    public void setCmd(int cmd) {
        this.cmd = cmd;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    public Object getData() {
        return data;
    }
    public void setData(Object data) {
        this.data = data;
    }
    public Handler getHandler() {
        return handler;
    }
    public void setHandler(Handler handler) {
        this.handler = handler;
    }
    @Override
    public String toString() {
        return "ServiceModel{" +
                "code=" + code +
                ", cmd=" + cmd +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                ", handler=" + handler +
                '}';
    }
}
app/src/main/java/com/fbo2206/MySocketClientThread.java
New file
@@ -0,0 +1,742 @@
package com.fbo2206;
import android.os.Looper;
import android.os.Message;
import com.comm.ServiceModel;
import com.fbs9100.ComFn;
import com.fbs9100.Ecb_Aes;
import com.fbs9100.FBS_CapState;
import com.fbs9100.FBS_ChargeState;
import com.fbs9100.FBS_Cmd;
import com.fbs9100.FBS_ComBase;
import com.fbs9100.FBS_ComBuf;
import com.fbs9100.FBS_ParamBatt;
import com.fbs9100.FBS_ParamCharge;
import com.fbs9100.FBS_ParamDischarge;
import com.fbs9100.FBS_ParamSystem;
import com.fbs9100.FBS_ResCapData;
import com.fbs9100.FBS_ResState;
import com.fbs9100.FBS_VCData;
import com.google.gson.Gson;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Date;
import com.fbo2206.FBO_ParamDischarge;
import com.fbo2206.FBO_ReadData;
import com.fbs9100.ComFn;
import com.fbs9100.Ecb_Aes;
import com.fbs9100.FBS_CapState;
import com.fbs9100.FBS_ChargeState;
import com.fbs9100.FBS_Cmd;
import com.fbs9100.FBS_ComBase;
import com.fbs9100.FBS_ComBuf;
import com.fbs9100.FBS_ParamBatt;
import com.fbs9100.FBS_ParamCharge;
import com.fbs9100.FBS_ParamDischarge;
import com.fbs9100.FBS_ParamSystem;
import com.fbs9100.FBS_ResCapData;
import com.fbs9100.FBS_ResState;
import com.fbs9100.FBS_VCData;
import com.google.gson.Gson;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Date;
import android.os.Handler;
import android.util.Log;
/**
     * Created by LiJun on 2019-04-28.
     */
    public class MySocketClientThread extends Thread implements Serializable
    {
        private FBS_Cmd m_FBS_Cmd = new FBS_Cmd();
        private FBS_VCData m_FBS_VCData = new FBS_VCData();
        private FBS_ParamBatt m_FBS_BattParam = new FBS_ParamBatt();
        private FBS_ParamSystem m_FBS_SystemParam = new FBS_ParamSystem();
        private FBS_ParamDischarge m_FBS_DiscParam = new FBS_ParamDischarge();
        private FBS_ParamCharge m_FBS_ChargeParam = new FBS_ParamCharge();
        private FBS_ResState m_ResTestState = new FBS_ResState();
        private FBS_CapState m_CapTestState = new FBS_CapState();
        private FBS_ChargeState m_ChrTestState = new FBS_ChargeState();
        public FBO_ParamDischarge fbo_DiscParam = new FBO_ParamDischarge();
        public FBO_ReadData fbo_ReadData = new FBO_ReadData();
        private FBS_ResCapData m_FBS_BaseData = new FBS_ResCapData();               //单体基础数据
        private FBS_ResCapData m_FBS_ResCapData = new FBS_ResCapData();             //单体内阻数据
        private FBS_ResCapData m_FBS_TmpCapData  = new FBS_ResCapData();            //单体温度数据
        private static final String TAG = "SocketClient_Thread";
        private ServiceModel revicemodel;
        private ServiceModel returnmodel;
        public static String server_ip = "127.0.0.1";            //设备iP
        public static int server_port = 9006;                    //设备监听断开
        private ByteBuffer sendByteBuffer = ByteBuffer.allocate(0);
        private ByteBuffer bytebuffer_for_socket_RX = ByteBuffer.allocate(1500);
        private boolean thread_run_flag = true;
        public static Socket socket;
        public static Date lastConTime = new Date();
        private static volatile com.comm.MyWebSocketTestThread client = null;
        public Handler mHandler = null;
        /*********************************************************************************************/
        public MySocketClientThread() {
            //initConnectDevice();
        }
    /*public static SerialPortSocketClient createSerialPortSocketClient(){
        if(client == null){
            synchronized (SerialPortSocketClient.class) {
                if(client == null){
                    client = new SerialPortSocketClient();
                }
            }
        }
        return client;
    }*/
        /*********************************************************************************************/
    public void run()
    {
        //初始化消息循环队列,需要在Handler创建之前
        Looper.prepare();
        mHandler = new Handler()
        {
            public void handleMessage(Message msg)
            {
                ServiceModel model = (ServiceModel)msg.obj;
                Log.e(TAG, "handleMessage: @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" +model);
                try
                {
                    if(null != model.handler)
                    {
                        ServiceModel remodel = new ServiceModel();
                        if(true == SocketComm(model.cmd, (ByteBuffer)(model.createByteBuffer()), remodel))
                        {
                            remodel.cmd = m_FBS_Cmd.CMD;
                            //--------------- 新建消息与句柄 -----------------
                            Handler handler = model.handler;
                            Message toMain = handler.obtainMessage();
                            toMain.obj = remodel;
                            handler.sendMessage(toMain);
                            //-----------------------------------------------
                            sleep(100);
                        }else{
                            remodel.cmd = model.cmd;
                            //--------------- 新建消息与句柄 -----------------
                            Handler handler = model.handler;
                            Message toMain = handler.obtainMessage();
                            toMain.obj = remodel;
                            handler.sendMessage(toMain);
                        }
                    }
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
        };
        //启动子线程消息循环队列
        Looper.loop();
    }
        /*********************************************************************************************/
    /*
    public boolean isConnect(Context context)
    {
        try
        {
            ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null)
            {
                // 获取网络连接管理的对象
                NetworkInfo info = connectivity.getActiveNetworkInfo();
                if ((info != null) && info.isConnected())
                {
                    // 判断当前网络是否已经连接
                    if(info.getState() == NetworkInfo.State.CONNECTED)
                        return true;
                }
            }
        }
        catch (Exception e)
        {
            Log.v("error",e.toString());
        }
        return false;
    }
    */
        /**
         *     向指定的socket通道发送数据,以及接收数据
         * @return
         */
        public boolean SocketComm(int cmd,ByteBuffer byteBuffer,ServiceModel model)
        {
            boolean res_t = false;
            InputStream in = null;
            OutputStream out = null;
            try
            {
                Thread.sleep(2000);
                socket = new Socket(server_ip, server_port);
                if(this.socket != null)
                {
                    in = this.socket.getInputStream();
                    out = this.socket.getOutputStream();
                    //----------------- clear rx buff for tcp resend packet ----------------//
                    byte[] rx_buf_t = new byte[1024];
                    //----------------------------------------------------------------------//
                    bytebuffer_for_socket_RX.order(ByteOrder.LITTLE_ENDIAN);
                    bytebuffer_for_socket_RX.clear();
                    //--------------------- socket write -----------------------------------//
                    //--------------------- socket write -----------------------------------//
                    boolean aes_en = false;
                    byte[] plain_tx_t = makeCommBuf(cmd, byteBuffer, aes_en);
                    byte[] cipher_tx_t = new byte[plain_tx_t.length];
                    Ecb_Aes my_aes = new Ecb_Aes();
                    my_aes.ecb_encrypt(plain_tx_t, cipher_tx_t, plain_tx_t.length);
                    Date d1 = new Date();
                    //=====================================================================//
                /*
                for(int n=0; n<3; n++) {
                    out.write(b);
                    out.flush();
                    //-----------------------------------------------------------------//
                    try {
                        while(true) {
                            int rx_len_t = in.read(rx_buf_t);
                            if(rx_len_t > 0) {
                                if((bytebuffer_for_socket_RX.position()+rx_len_t)
                                        < (bytebuffer_for_socket_RX.capacity()-16)) {
                                    bytebuffer_for_socket_RX.put(rx_buf_t, 0, rx_len_t);
                                }
                            }
                            if(bytebuffer_for_socket_RX.position() > 8) {
                                break;
                            }
                        }
                    } catch (SocketTimeoutException soe) {
                        //soe.printStackTrace();
                    }
                    //-----------------------------------------------------------------//
                }
                //=====================================================================//
                */
                    int rx_read_time_out = 0;
                    //int rx_len = 0;
                    System.out.println("数据长度" + plain_tx_t.length + "\t发送数据:" + ComFn.bytesToHexString(plain_tx_t, plain_tx_t.length));
                    out.write(plain_tx_t);
                    out.flush();
                    while(true) {
                        if(in.available() > 0) {
                            rx_read_time_out = 0;
                            int rx_len_t = in.read(rx_buf_t);
                            if((bytebuffer_for_socket_RX.position()+rx_len_t)
                                    < (bytebuffer_for_socket_RX.capacity()-1)) {
                                bytebuffer_for_socket_RX.put(rx_buf_t, 0, rx_len_t);
                            }
                            //bytebuffer_for_socket_RX.put((byte)in.read());
                        } else {
                            rx_read_time_out++;
                            if((bytebuffer_for_socket_RX.position() >= 8) && (rx_read_time_out>10)){
                                //    res = true;
                                break;
                            }
                            if(rx_read_time_out > 220) {
                                break;
                            }
                        }
                        Thread.sleep(10);
                    }
                    bytebuffer_for_socket_RX.flip();
                    Date d2 = new Date();
                    long comm_tms = (d2.getTime() - d1.getTime());
                    if(comm_tms < 200) {
                        Thread.sleep(200 - comm_tms);
                    }
                /*
                System.out.println(this.getName()
                                    + "  dev_id: " + m_StatAndParam.dev_id
                                    + "  d2-d1:" + (comm_tms)+"ms"
                                    + "  rx_len:" + bytebuffer_for_socket_RX.limit()
                                    + "  tx_count:" + m_FBS_VCData.m_SysState.CommCount
                                    + "  rx_err_sum:" + m_FBS_VCData.m_SysState.ErrCommCount
                                    + "  rx_err_count:" + rx_errcount_for_live_of_thread
                                    + Com.getNowTimeWithAt());
                */
                    byte[] cipher_buf = new byte[bytebuffer_for_socket_RX.limit()];
                    byte[] plain_buf = new byte[bytebuffer_for_socket_RX.limit()];
                    bytebuffer_for_socket_RX.get(cipher_buf);
                    my_aes.ecb_decrypt(cipher_buf, plain_buf, cipher_buf.length);
                    System.err.println("数据长度"+cipher_buf.length+"\t返回数据:"+ComFn.bytesToHexString(cipher_buf, cipher_buf.length));
                    //Log.e(TAG, "SocketComm: "+ComFn.bytesToHexString(plain_buf, plain_buf.length));
                    if(true == getDataFromCommBuf(cipher_buf,model)) {
                        res_t = true;
                    /*
                    System.err.println(ComFn.bytesToHexString(buffer, buffer.length));
                    System.err.println(this.getName() + " DevId: " + m_StatAndParam.dev_id
                                            + "---- cmd:" + cmd  + " RxLen: " + buffer.length
                                            + " 通信失败" + Com.getNowTimeWithAt());
                     */
                        model.code = 1;
                    } else {
                        res_t = false;
                        model.code = 0;
                    }
                } else {
                    //System.out.println(this.getName() + "-------socket  异常关闭-------" + Com.getNowTimeWithAt());
                    thread_run_flag = false;
                }
            } catch (IOException | InterruptedException e) {
                thread_run_flag = false;
            } finally {
                if(in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(socket != null){
                    try {
                        socket.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return res_t;
        }
        /*********************************************************************************************/
//    @SuppressWarnings("finally")
//    public boolean SocketComm1(int cmd, ByteBuffer bf, MyWebSocketTestThread.ServiceModel msgobj) throws InterruptedException
//    {
//        boolean res = false;
//        try
//        {
//            //Socket socket = new Socket();
//            //socket.connect(new InetSocketAddress("192.168.1.48", 9001), 200);
//
//            if(this.socket != null)
//            {
//                InputStream in = socket.getInputStream();
//                OutputStream out = socket.getOutputStream();
//
//                out.write(makeCommBuf(cmd, bf,false));
//
//                for(int n=0; n<10; n++)
//                {
//                    sleep(10);
//                    int len1 = in.available();
//                    if(len1 <= 0)
//                        continue;
//
//                    sleep(10);
//
//                    if(in.available() == len1)
//                        break;
//                }
//
//                byte[] buffer = new byte[in.available()];
//                in.read(buffer);
//
//                msgobj.msg = getDataFromCommBuf(buffer);
//
//                in.close();
//                socket.close();
//                res = true;
//            }
//        }
//        catch (UnknownHostException e)
//        {
//            //e.printStackTrace();
//            msgobj.msg = e.getMessage();
//        }
//        catch (IOException e)
//        {
//            //e.printStackTrace();
//            msgobj.msg = e.getMessage();
//        }
//        finally
//        {
//            return res;
//        }
//    }
        /*********************************************************************************************/
        /*********************************************************************************************/
        public byte[] makeCommBuf(final int cmd, ByteBuffer bf, boolean aes_en)
        {
            ByteBuffer bbf = FBS_ComBuf.makeFbs9100CommBuf(0xFF, cmd, bf, aes_en);
            byte byte_rest[] = new byte[bbf.limit()];
            bbf.get(byte_rest);
            return byte_rest;
        }
        /*********************************************************************************************/
        public Boolean getDataFromCommBuf(final byte[] bytes,ServiceModel model)
        {
            boolean isSuccess = false;
            ByteBuffer bf = ByteBuffer.allocate(bytes.length);
            bf.order(ByteOrder.LITTLE_ENDIAN);
            bf.put(bytes);
            bf.flip();
            String msg = "";
            if(true == m_FBS_Cmd.putByteBuffer(bf))
            {
                lastConTime = new Date();
                //------------------- 开始通讯 --------------------
                if(FBS_ComBase.CMD_STARTCNNECT == m_FBS_Cmd.CMD
                        && FBS_ComBase.DataReturn_Successs == m_FBS_Cmd.RES_Index
                ) {
                    model.msg = "Connect Device Success !!!";
                    isSuccess = true;
                }
                //------------------- 读取FBS9100电压电流数据 --------------------
                else if(FBS_ComBase.CMD_GetVIData == m_FBS_Cmd.CMD)
                {
                    if(true == fbo_ReadData.putByteBuffer(bf)) {
                        System.out.println("读取实时数据成功:"+fbo_ReadData);
                        model.data = fbo_ReadData;
                        model.msg = "Get realdata from FBS9100 OK!!!";
                        isSuccess = true;
                    }
                /*if(true == m_FBS_VCData.m_SysState.putByteBuffer(bf))
                {
                    if(true == m_FBS_VCData.putByteBuffer(bf)){
                        returnmodel.data = m_FBS_VCData;
                        returnmodel.msg = "Get data from FBS9100 OK!!!";
                        isSuccess = true;
                    }
                }*/
                }
                //------------------- 读取FBS9100内阻测试状态 -----------------------
                if(FBS_ComBase.CMD_GetResTestState == m_FBS_Cmd.CMD)
                {
                    if(true == m_ResTestState.putByteBuffer(bf)) {
                        model.data = m_ResTestState;
                        model.msg = "Get ResTest State from FBS9100 OK!!!";
                        isSuccess = true;
                    }
                }
                //------------------- 读取FBS9100容量测试状态 -----------------------
                if(FBS_ComBase.CMD_GetDischargeState == m_FBS_Cmd.CMD)
                {
                    if(true == m_CapTestState.putByteBuffer(bf)) {
                        model.msg = "Get CapTest State from FBS9100 OK!!!";
                        model.data = m_CapTestState;
                        isSuccess = true;
                    }
                }
                //------------------- 读取FBS9100充电测试状态 -----------------------
                if(FBS_ComBase.CMD_GetChargeState == m_FBS_Cmd.CMD)
                {
                    if(true == m_ChrTestState.putByteBuffer(bf)) {
                        model.msg = "Get ChrTest State from FBS9100 OK!!!";
                        model.data = m_ChrTestState;
                        isSuccess = true;
                    }
                }
                //------------------- 读取FBS9100电池参数 -------------------------
                else if(FBS_ComBase.CMD_GetBattParam == m_FBS_Cmd.CMD)
                {
                    if(true == m_FBS_BattParam.putByteBuffer(bf)) {
                        model.msg = "Get battparam from FBS9100 OK!!!";
                        model.data = m_FBS_BattParam;
                        isSuccess = true;
                    }
                }
                //------------------- 设置FBS9100电池参数 -------------------------
                else if(FBS_ComBase.CMD_SetBattParam == m_FBS_Cmd.CMD)
                {
                    if(true == m_FBS_BattParam.putByteBuffer(bf)) {
                        model.msg = "Set battparam to FBS9100 OK!!!";
                        model.data = m_FBS_BattParam;
                        isSuccess = true;
                    }
                }
                //------------------- 读取FBS9100系统参数 -------------------------
                else if(FBS_ComBase.CMD_GetSYSSetParam == m_FBS_Cmd.CMD)
                {
                    if(true == m_FBS_SystemParam.putByteBuffer(bf)) {
                        model.msg = "Get sysparam from FBS9100 OK!!!";
                        model.data = m_FBS_SystemParam;
                        isSuccess = true;
                    }
                }
                //------------------- 设置FBS9100系统参数 -------------------------
                else if(FBS_ComBase.CMD_SetSYSSetParam == m_FBS_Cmd.CMD)
                {
                    if(true == m_FBS_SystemParam.putByteBuffer(bf)) {
                        model.msg = "Set sysparam to FBS9100 OK!!!";
                        model.data = m_FBS_SystemParam;
                        isSuccess = true;
                    }
                }
                //------------------- 读取FBS9100放电参数 -------------------------
                else if(FBS_ComBase.CMD_GetDischargeParm == m_FBS_Cmd.CMD)
                {
                    //System.out.println("获取FBO参数");
                    if(true == fbo_DiscParam.putByteBuffer(bf)){
                        System.out.println("读取放电参数成功" + fbo_DiscParam);
                        model.msg = "Get DischargeParm from FBS9100S OK!!!";
                        model.data = fbo_DiscParam;
                        isSuccess = true;
                    }
                }
                //------------------- 设置FBS9100放电参数 -------------------------
                else if(FBS_ComBase.CMD_SetDischargeParm == m_FBS_Cmd.CMD)
                {
                    System.out.println("设置放电参数");
                    if(FBS_ComBase.DataReturn_Successs == m_FBS_Cmd.RES_Index){
                        System.out.println("设置放电参数成功:" + fbo_DiscParam);
                        model.msg = "Set DischargeParam to FBS9100 OK!!!";
                        model.data = fbo_DiscParam;
                        isSuccess = true;
                    }
                }
                //------------------- 读取FBS9100充电参数 -------------------------
                else if(FBS_ComBase.CMD_GetChargeParm == m_FBS_Cmd.CMD)
                {
                    if(true == m_FBS_ChargeParam.putByteBuffer(bf)){
                        model.msg = "Get ChargeParam from FBS9100 OK!!!";
                        model.data = m_FBS_ChargeParam;
                        isSuccess = true;
                    }
                }
                //------------------- 设置FBS9100充电参数 -------------------------
                else if(FBS_ComBase.CMD_SetChargeParm == m_FBS_Cmd.CMD)
                {
                    if(true == m_FBS_ChargeParam.putByteBuffer(bf)){
                        model.msg = "Set ChargeParam to FBS9100 OK!!!";
                        model.data = m_FBS_ChargeParam;
                        isSuccess = true;
                    }
                }
                //------------------- 读取FBS9100内阻温度测试数据 ------------------
                else if((FBS_ComBase.CMD_GetMonomerRES == m_FBS_Cmd.CMD)
                        ||(FBS_ComBase.CMD_GetMonomerTMP == m_FBS_Cmd.CMD)
                    /*||(FBS_ComBase.CMD_GetMonomerCAP == m_FBS_Cmd.CMD)
                    ||(FBS_ComBase.CMD_GetMonomerChargeCAP == m_FBS_Cmd.CMD)*/)
                {
                    if(true == m_FBS_BaseData.putByteBuffer(bf, m_FBS_Cmd.CMD)) {
                        //getFBS9100MonResData(m_FBS_Cmd.CMD, m_FBS_ResCapData);
                        model.msg = "Get MonomerRES or MonomerTMP from FBS9100 OK!!!";                         //获取单体内阻和单体温度数据成功
                        model.data = m_FBS_BaseData;
                        isSuccess = true;
                    }
                }
                //-------------------  启动内阻测试启动核容测试成功 ---------------------------------------------
                else if((FBS_ComBase.CMD_StartDischarge == m_FBS_Cmd.CMD)
                        || (FBS_ComBase.CMD_StartResDischarge == m_FBS_Cmd.CMD)
                        &&(FBS_ComBase.DataReturn_Successs == m_FBS_Cmd.RES_Index)
                ){
                    System.out.println("启动放电成功");
                    model.msg = "Start MonomerRESTest or MonomerCapTest from FBS9100 OK!!!";
                    isSuccess = true;
                }
                //-------------------  启动充电测试     ---------------------------------------------
                else if(FBS_ComBase.CMD_StartCharge == m_FBS_Cmd.CMD
                        && (FBS_ComBase.DataReturn_Successs == m_FBS_Cmd.RES_Index)
                ){
                    System.out.println("启动充电成功");
                    model.msg = "Start MonomerChargeTest from FBS9100 OK!!!";
                    isSuccess = true;
                }
                //-------------------- 停止测试成功 -----------------------------------------
                else if(FBS_ComBase.CMD_Stop == m_FBS_Cmd.CMD
                        && (FBS_ComBase.DataReturn_Successs == m_FBS_Cmd.RES_Index)
                ){
                    System.out.println("停止成功");
                    model.msg = "Stop MonomerCapTest from FBS9100 OK!!!";
                    isSuccess = true;
                }
                //-------------------- 暂停测试成功 -----------------------------------------
                else if(FBS_ComBase.CMD_Suspended == m_FBS_Cmd.CMD
                        && (FBS_ComBase.DataReturn_Successs == m_FBS_Cmd.RES_Index)
                ){
                    System.out.println("暂停成功");
                    model.msg = "Suspended MonomerCapTest from FBS9100 OK!!!";
                    isSuccess = true;
                }
            }
            return isSuccess;
        }
        /**
         * 根据指定的命令给制定的但他数据赋值
         * @param cmd
         * @param res_data
         */
        private void getFBS9100MonResData(int cmd, FBS_ResCapData res_data)
        {
            int mon_index = 0;
            if(null != m_FBS_BaseData)
            {
                if(FBS_ComBase.CMD_GetMonomerRES == cmd) {
                    m_FBS_ResCapData = m_FBS_BaseData.clone();
                    //Log.d(TAG, "getFBS9100MonResData: 获取单体内阻数据成功。。。");
                } else if(FBS_ComBase.CMD_GetMonomerTMP == cmd) {
                    m_FBS_TmpCapData = m_FBS_BaseData.clone();
                    //Log.d(TAG, "getFBS9100MonResData: 获取单体内阻数据成功。。。");
                }
            }
        }
        public FBS_ResCapData getM_FBS_ResCapData() {
            return m_FBS_ResCapData;
        }
        public FBS_ResCapData getM_FBS_TmpCapData() {
            return m_FBS_TmpCapData;
        }
        /**
         * js前台接收返回数据
         * @return
         */
        public String getServiceModel() {
            Gson gson = new Gson();
            return gson.toJson(returnmodel);
        }
        /**
         * js前台传入的数据
         * @param json
         */
        public void setServiceModel(String json) {
            Gson gson = new Gson();
            revicemodel = gson.fromJson(json, ServiceModel.class);
            sendByteBuffer = ByteBuffer.allocate(0);
            if(revicemodel.cmd == FBS_ComBase.CMD_SetDischargeParm) {
                //设置放电参数时
                FBO_ParamDischarge param = (FBO_ParamDischarge)revicemodel.data;
                sendByteBuffer = param.getByteBuffer();
            }
        }
        public void setFBO2206Param(com.comm.MyWebSocketTestThread therad) {
            FBO_ParamDischarge param = therad.fbo_DiscParam;
            param.test_mode = 1;                //放电模式  0-离线放电             1在线放电
            param.acstop_op = 1;                //停电处理    0-停止放电            1继续放电
            param.nominal_cap = 300;            //标称容量
            param.hourly_rate = 10 ;            //小时率
            param.preset_cur = 20;                //预放电流        (0.1)
            param.preset_cap = 50;                //预放容量
            param.preset_time = 60;                //预放时间(分钟)
            param.mon_lower = 10.8;                //单体下限        (0.01)
            param.group_lower = 45;                //组端下限        (0.1)
            param.mon_number = 12;                //单体数量
            param.group_number = 4;                //电池组数
            param.lower_number = 5;                //单体下限个数
            param.mon_vol = 12;                    //标称单体电压
            param.booster_ceiling = 56;            //升压上限
            param.charge_limit =  20;            //充电电流        (0.1)
            param.onlinevol_lowlimit = 60 ;        //在线阀值        (0.1)
            param.battName = "新建";            //电池组名称
            sendByteBuffer = fbo_DiscParam.getByteBuffer();
        }
        /**
         * 修改服务器的ip和通讯的端口号
         * @param server_ip         服务器IP
         * @param server_port       服务器端口号
         */
        public void setServerParam(String server_ip,int server_port){
            this.server_ip = server_ip;
            this.server_port = server_port;
        }
        public static void main(String[] args) {
            com.comm.MyWebSocketTestThread thread = new com.comm.MyWebSocketTestThread();
            ServiceModel model = new ServiceModel();
            //thread.server_ip = "192.168.1.126";
            //thread.server_port = 9600;
            //thread.revicemodel = model;
            model.cmd = FBS_ComBase.CMD_STARTCNNECT;                //开始通讯
            thread.SocketComm();
            //thread.setFBO2206Param(thread);
            //model.cmd = FBS_ComBase.CMD_SetDischargeParm;            //设置放电参数
            model.cmd = FBS_ComBase.CMD_GetDischargeParm;            //获取放电参数
            model.cmd = FBS_ComBase.CMD_GetVIData;                    //获取电池组状态
            thread.SocketComm();
        }
        /*********************************************************************************************/
    /********************************* end of file SocketClient1.java *************************************/
}
app/src/main/java/com/fbs9100/FBS_ComBase.java
@@ -6,7 +6,8 @@
    public static final int     MonomerCountMax                    =    480;
    public static final int     FBOMonomerCountMax                 =   300;
    public static final int     CMD_STARTCNNECT                   =   0x01;
    public static final int     CMD_STARTCNNECT                   =   0x01;            //开始通信
    public static final int     CMD_SETDEVICEIP                =   0x02;            //设置设备ip
    //----------------------------------------------------------------------------
    public static final int     CMD_NULL                        =    0x00;
app/src/main/res/layout/index_layout.xml
New file
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <WebView
        android:id="@+id/my_webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        ></WebView>
</LinearLayout>