whyclj
2019-06-24 7db82bcad74395c674a373b4d178d122eed3006b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package com.dev.btse.data;
 
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
 
import com.battmonitor.base.Com;
import com.battmonitor.base.ComBase;
import com.battmonitor.sql.MysqlConnPool;
 
public class TmpSensor_SocketThread extends Thread{
    private static final int autoUpdateTime = 4;
    private static final int maxTmpSensorCount = 32;
    
    private List<TmpSensorState> tmpSensors = new ArrayList<TmpSensorState>();                //±äËÍÆ÷ÖеÄËùÓд«¸ÐÆ÷״̬
    
    private Socket m_socket;
    private MysqlConnPool pool;
    private boolean hadreg_flag = false;
    private TmpSensorState tmpState = new TmpSensorState();
    private TmpSensor_inf tmpinf;
    
    private TmpSensor_Cmd m_TMP_Cmd = new TmpSensor_Cmd();
    private boolean S_thread_run_flag = true;
    private int rx_errcount_for_live_of_thread = 0;        //ÓÃÓÚͳ¼ÆsocketͨÐÅÖеÄÒì³£´ÎÊýͳ¼Æ
    private ByteBuffer bytebuffer_for_socket_RX = ByteBuffer.allocate(1500);
    
    public TmpSensor_SocketThread(Socket m_socket,MysqlConnPool pool) {
        this.m_socket = m_socket;
        this.pool = pool;
        for(int i=0;i<maxTmpSensorCount;i++) {
            tmpSensors.add(new TmpSensorState());
        }
    }
    
    public void initDev_addr() {
        try {
            for(int i = 0;i<5;i++) {
                if(!hadreg_flag) {
                    SocketComm(TmpSensor_ComBase.CMD_READDATAFROMMODBUS,TmpSensor_ComBase.CMD_DEVICEID_ADDR,createSingleBuffer(1) , this.m_socket);
            
                    Thread.sleep(200);
                    rx_errcount_for_live_of_thread = 0;
            
                }else {
                    System.out.println("»ñÈ¡É豸id³É¹¦"+tmpState.sensor_dev_id+Com.getDateTimeFormat(new Date(), Com.DTF_YMDhms));
                    break;
                }
                System.out.println(i+""+tmpState.getSensor_dev_id());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public void run() {
        System.out.println("TmpSensor_SocketThread start at "+Com.getDateTimeFormat(new Date(), Com.DTF_YMDhms));
        
        initDev_addr();                        //ʶ±ðµ±Ç°É豸ÊÇ·ñΪζȴ«¸ÐÆ÷
        
        TmpSensor_inf tmpinf = TmpSensor_SQL.queryTmpSensorById(pool, tmpState.getSensor_dev_id());
        
        int cnt = 1;
        while(S_thread_run_flag && tmpinf != null) {
            try {
                if(cnt%7 == 0) {
                    /************************  »ñÈ¡´«¸ÐÆ÷ʵʱµÄ״̬ÐÅÏ¢Êý¾Ý   *******************************************************/
                    SocketComm(TmpSensor_ComBase.CMD_READDATAFROMMODBUS,TmpSensor_ComBase.CMD_GETTMPSENSORSTATE,tmpState.getReadBuffer() , this.m_socket);
                }
                cnt ++;
                sleep(autoUpdateTime * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
    
    /**
     * ÏòÖ¸¶¨µÄsocketͨµÀ·¢ËÍÊý¾Ý£¬ÒÔ¼°½ÓÊÕÊý¾Ý
     * @param cmd        
     * @param bf
     * @return
     * @throws InterruptedException
     */
    
    public boolean SocketComm(int cmd,int reg_index, ByteBuffer bf, Socket socket) throws InterruptedException
    {
        boolean res_t = false;
        try {
            socket.setSoTimeout(3000);
            if(S_thread_run_flag) {
                InputStream in = socket.getInputStream();
                OutputStream out = socket.getOutputStream();
                //----------------- clear rx buff for tcp resend packet ----------------//
                byte[] rx_buf_t = new byte[1024];
                /*
                int buf_clr_read_count = 0;
                while(in.available() > 0) {
                    in.read(rx_buf_t);
                    if(buf_clr_read_count >= 10) {
                        S_thread_run_flag = false;
                        System.err.println(this.getName()
                                            + " dev_id: " + m_StatAndParam.dev_id 
                                            + " socket rx_buff clear error......");
                        res_t = false;
                        return res_t;
                    }
                }*/
                //----------------------------------------------------------------------//
                //--------------------- socket write -----------------------------------//
                byte[] cipher_tx_t = null;
                Ecb_Aes my_aes = new Ecb_Aes();
                if(reg_index == FBS9100_ComBase.CMD_ReadGPRSCSQ) {
                    cipher_tx_t = new byte[bf.limit()];
                    bf.get(cipher_tx_t);
                } else {
                    cipher_tx_t = makeCommBuf(cmd,reg_index, bf, false);
                    
                }
                //System.err.println(ComFn.bytesToHexString(cipher_tx_t, cipher_tx_t.length));
                //=====================================================================//
                Date d1 = new Date();
                int rx_read_time_out = 0; 
                out.write(cipher_tx_t);
                out.flush();
                
                bytebuffer_for_socket_RX.order(ByteOrder.BIG_ENDIAN);
                bytebuffer_for_socket_RX.clear();
                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);
                        }
                    } else { 
                        rx_read_time_out += 1;
                        if((bytebuffer_for_socket_RX.position()>=7) && (rx_read_time_out>10)){
                            res_t = 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
                                    + "  cmd:" + cmd
                                    + "  d2-d1:" + (comm_tms)+"ms"
                                    + "  rx_len:" + bytebuffer_for_socket_RX.limit()
                                    //+ "  tx_count:" + m_StatAndParam.m_FBS_VCData.m_SysState.CommCount
                                    //+ "  rx_err_sum:" + m_StatAndParam.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(plain_buf);
                //System.out.println(ComFn.bytesToHexString(plain_buf, plain_buf.length));
                if(cmd == FBS9100_ComBase.CMD_ReadGPRSCSQ) {
                    if(bytebuffer_for_socket_RX.limit() > 2) {
                        rx_errcount_for_live_of_thread = 0;
                        res_t = true;
                        
                        //m_StatAndParam.m_GPRS_inf = new String(cipher_buf);
                        //System.out.println("this.getName() + " + " DevId: " + m_StatAndParam.dev_id
                        //                    + " GPRS RF Level:" + m_StatAndParam.m_GPRS_CSQ);
                    }
                } else {
                    m_TMP_Cmd.RES_Index = reg_index;
                    if((cipher_buf.length >= 7) && (true == getDataFromCommBuf(plain_buf))) {
                        tmpState.setDev_commcount();
                        rx_errcount_for_live_of_thread = 0;
                        res_t = true;
                    } else {
                        res_t = false;
                        tmpState.setDev_errcommcount();
                        rx_errcount_for_live_of_thread++;
                        //m_StatAndParam.m_SysState.setErrCommCountInc(bytebuffer_for_socket_RX.limit());
                    }
                }
            } else {
                S_thread_run_flag = false;
                tmpState.setDev_errcommcount();
            }
        } catch (IOException e) {
            //e.printStackTrace();
            tmpState.setDev_errcommcount();
            S_thread_run_flag = false;
        } finally {
            //ÈôÔÚͨÐŵĹý³ÌÖгöÏÖÁ¬Ðø5´ÎͨÐÅÒì³£¹Ø±ÕÁ¬½Ó
            if(rx_errcount_for_live_of_thread >= 5){
                S_thread_run_flag = false;
            }
        }
        return res_t;
    }
    
    private boolean getDataFromCommBuf(byte[] bytes) {
        boolean isSuccess = false;
        ByteBuffer bf = ByteBuffer.allocate(bytes.length);
        bf.order(ByteOrder.BIG_ENDIAN);
        bf.put(bytes);
        bf.flip();
        if(true == m_TMP_Cmd.putByteBuffer(bf)) {
            //System.out.println(m_TMP_Cmd);
            if(TmpSensor_ComBase.CMD_GETTMPSENSORSTATE == m_TMP_Cmd.RES_Index) {
                /*********************** »ñÈ¡´«¸ÐÆ÷µÄʵʱ״̬ÐÅÏ¢    *****************************************************/
                if(true == tmpState.putByteBuffer(bf)) {
                    System.out.println(tmpState);
                    isSuccess = true;
                    TmpSensor_SQL.insertOrUpdateTmpSensorState(pool, tmpState);                    //¸üÐÂÊý¾Ý¿âÖеĴ«¸ÐÆ÷״̬
                }
            }else if(TmpSensor_ComBase.CMD_DEVICEID_ADDR == m_TMP_Cmd.RES_Index) {
                /************************ »ñÈ¡´«¸ÐÆ÷É豸µÄid *******************************************************/
                hadreg_flag = true;
                int addr_id = ComBase.changeShortToInt(bf.getShort());
                tmpState.createTmpDevid(addr_id);
            }
        }else {
            System.err.println(1111);
        }
        return isSuccess;
    }
 
    /*********************************************************************************************/
    /*
     *    ¹¹Ôì·¢ËÍÊý¾Ý
     */
    public byte[] makeCommBuf(final int cmd,int reg_index, ByteBuffer bf, boolean aes_en)
    {
        ByteBuffer bbf = TmpSensor_ComBuf.makeTmpSensorCommBuf(0x01, cmd,reg_index, bf, aes_en);
        byte byte_rest[] = new byte[bbf.limit()];
        bbf.get(byte_rest);
        return byte_rest;
    }
    /*********************************************************************************************/
    
    
    public ByteBuffer createSingleBuffer(int regcount) {
        ByteBuffer tmp = ByteBuffer.allocate(2);
        tmp.order(ByteOrder.BIG_ENDIAN);
        tmp.putShort(ComBase.changeIntToShort(regcount));
        tmp.flip();
        return tmp;
    }
    
    public static void main(String[] args) {
        Socket socket;
        try {
            
            MysqlConnPool pool = new MysqlConnPool("127.0.0.1", 3360,100);
            socket = new Socket("118.89.139.230",8919);
            TmpSensor_SocketThread thread = new TmpSensor_SocketThread(socket,pool);
            thread.start();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}