充放电一体机二期通信程序【在用】
Administrator
2022-07-23 a7e17aa6cae5aac8f6e1b0158c15942cdd038228
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
package com.dev.fgcd.data;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Date;
 
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
 
import com.battmonitor.base.Com;
import com.battmonitor.sql.MysqlConnPool;
import com.dev.btse.data.ComFn;
import com.dev.fgcd.comm.FGCD_Task_Thread_SQL;
 
 
/**
 *     ³ä·ÅµçÒ»Ìå»úÔ¶³ÌÉý¼¶¶ÔÏó
 * @author LiJun
 *
 */
public class FGCD_DFU_State {
    private int DFU_BUF_LEN = 1024;
    
    public static final int DFU_STATE_NULL = 0;
    public static final int DFU_STATE_WRITE = 1;
    public static final int DFU_STATE_READ = 2;
    public static final int DFU_STATE_CHECK_OK = 3;    
    
    
    public static final int DFU_En_Stop     = 0;            //Í£Ö¹Éý¼¶
    public static final int DFU_En_Running     = 1;            //Éý¼¶ÖÐ
    public static final int DFU_En_Success  = 2;            //Éý¼¶Íê³É
    public static final int DFU_En_Error    = 3;            //Éý¼¶Ê§°Ü
    
    public static final int Error_Code_Null = 0;            //ÎÞ
    public static final int Error_Code_FileNotFound = 1;    //ÎļþûÕÒµ½
    public static final int Error_Code_ParamError     = 2;    //²ÎÊý´íÎó
    public static final int Error_Code_TimeOut = 3;            //·¢ËÍÎļþ³¬Ê±
    public static final int Error_Code_RemoteStop = 4;        //Ô¶³ÌÍ£Ö¹
    
    
    
    private ByteBuffer bytebuffer_for_socket_RX = ByteBuffer.allocate(1200);
    
    public int dev_id;                    //É豸ID
    public String dfu_file;                //ÎļþÃû
    public int dfu_en;                //Éý¼¶Ê¹ÄÜ0:²»Éý¼¶|Í£Ö¹Éý¼¶
    public int dfu_wr_stat;                //µ±Ç°Éý¼¶×´Ì¬0£ºÉý¼¶Íê³É;1:¶Á;2:д
    public int dfu_data_blocknum;        //µ±Ç°¶ÁÈ¡µÄ°ü±àºÅ
    public int dfu_data_blocklen;        //Êý¾Ý°ü×ܸöÊý
    public String dfu_password;            //ÃÜÂë
    public int dfu_file_len;            //Éý¼¶Îļþ×ܳ¤¶È
    private Logger logger;
    private MysqlConnPool pool;
    private FGCD_Cmd m_FBS_Cmd = new FGCD_Cmd();
    private boolean start_ok = false;                //ÒÑÆô¶¯¿ªÊ¼·¢ËÍ
    
    public int DataBlockNum = 0;        //ÏìÓ¦µÄµ±Ç°Òѳɹ¦Êý¾ÝÖ¡ºÅ
    public int DataLen = 0;                //ÏìÓ¦µÄ×ÜÖ¡Êý
    
    private int comm_error_count = 0;
    public int now_datablock_num = 0;                //¿ªÊ¼·¢ËͰüË÷Òý
    
    public String sysVersion_new;       //---µ±Ç°°æ±¾ºÅ
    public String sysVersion_dev;       //---ÉÏÒ»´ÎÉý¼¶Ê±µÄ°æ±¾ºÅ
    
    public int error_code = Error_Code_Null;
    
    public FGCD_DFU_State(MysqlConnPool pool) {
        this.pool = pool;
        this.logger = LogManager.getLogger(this.getClass());
    }
 
    public boolean check_If_DFU_Is_Eanbled() {
        boolean res_t = false;
        comm_error_count = 0;
        if(DFU_En_Running != this.dfu_en) {
            res_t = false;
        } else {
            res_t = true;            
            if(DFU_STATE_WRITE != this.dfu_wr_stat) {
                logger.warn("DFU_WR_State must is DFU_STATE_READ");
                error_code = Error_Code_ParamError;
                res_t = false;
            }
            if(this.dfu_data_blocknum <= 0) {
                logger.warn("DFU_DataBlockNum_Start must bigger then Zero");
                error_code = Error_Code_ParamError;
                res_t = false;
            }            
            File f = new File(this.dfu_file);
            if(false == f.exists()) {
                error_code = Error_Code_FileNotFound;
                res_t = false;
                logger.warn(" A059 DFU_File '" + this.dfu_file + "' Not Exist");
            }
            
            if(!res_t) {
                //ÓдíÎóʱÐèҪֹͣÉý¼¶²¢¸æËßµ±Ç°´íÎó´úÂë[Òª²»È»»áÒ»Ö±½øÀ´¼ì²â]
                this.dfu_en = DFU_En_Error;
                FGCD_Task_Thread_SQL.updateFbs9100S_DFU_StatByDev_Id(pool, this);
            }
        }        
        return res_t;
    }
    
 
    //¿ªÊ¼Éý¼¶
    public boolean runDFU(Socket socket) {
        //--------------------------- BOOTLOADER_CMD_WRITE-----------------------------//
        String dfu_text_inf = String.format("DevId:%d DFU Update Start ...", this.dev_id);
        logger.warn(dfu_text_inf);
        //dt_show_msg.setText(dfu_text_inf);
        FileInputStream fis = null;
        this.error_code = Error_Code_Null;
        boolean isSuccess = false;
        try {
            File f = new File(this.dfu_file);                    
            this.dfu_file_len = (int) f.length();                                                    //Îļþ×ܳ¤¶È
            this.dfu_data_blocklen = (int)Math.ceil((double)this.dfu_file_len/DFU_BUF_LEN);            //Êý¾ÝÖ¡×ܸöÊý
            logger.info("DevId:" + dev_id + "\tÊý¾ÝÖ¡×ÜÊý:" + this.dfu_data_blocklen + "\tÎļþ×ܳ¤¶È£º" + this.dfu_file_len);
            
            byte[] buf_to_flash = new byte[this.DFU_BUF_LEN];
            Thread.sleep(100);
            fis = new FileInputStream(f);
            now_datablock_num = 0;
            while(true) {
                FGCD_Task_Thread_SQL.queryFbs9100S_DFU_StateBydev_id(pool,this);
                if(DFU_En_Error == this.dfu_en) {
                    //Ô¶³ÌÍ£Ö¹
                    dfu_text_inf = String.format("DevId:%d DFU Remote Stop " + Com.getNowTimeWithAt(), this.dev_id);
                    logger.info(dfu_text_inf);    
                    this.error_code = Error_Code_RemoteStop;
                    break;
                }
                
                if(!start_ok) {
                    //ÐèÒª·¢ËÍ¿ªÊ¼·¢ËÍÎļþ            
                    SocketComm(FGCD_ComBase.CMD_STARTSysUpdate,this.dfu_data_blocklen,now_datablock_num,socket,new byte[]{});
                    Thread.sleep(20);
                }
                int data_len_towrite = 0;
                //System.out.println(now_datablock_num +" === "+dfu_data_blocknum);
                while(now_datablock_num < this.dfu_data_blocknum)
                {
                    //µ±Ç°·¢Ë͵ÄÊý¾ÝÖ¡ºÅ²»µÈÓÚÓ¦¸Ã·¢Ë͵Ä֡ʱ¼ÌÐø¶ÁÈ¡µ±Ç°Ö¡
                    for(int n=0; n<buf_to_flash.length; n++) {
                        buf_to_flash[n] = (byte) 0xFF;
                    }
                    data_len_towrite = fis.read(buf_to_flash);
                    if(data_len_towrite <= 0) {
                        break;
                    } else {
                        now_datablock_num += 1;
                    }
                }
                if(now_datablock_num <= this.dfu_data_blocklen && start_ok) {
                    if(data_len_towrite < DFU_BUF_LEN && data_len_towrite>0) {
                        //×îºóÒ»Ö¡³¤¶ÈСÓÚ1024ʱ
                        byte[] data = new byte[data_len_towrite];
                        System.arraycopy(buf_to_flash, 0, data, 0, data_len_towrite);
                        buf_to_flash = data;
                    }
                    //·¢ËÍÉý¼¶Îļþ
                    for(int cnt=0;cnt<3;cnt++) {                        
                        boolean flag = SocketComm(FGCD_ComBase.CMD_SendUpdateFile,this.dfu_data_blocklen,now_datablock_num-1,socket,buf_to_flash);
                        if(flag) {
                            Thread.sleep(10);
                            break;
                        }else {
                            Thread.sleep(5000);
                        }
                    }
                    
                }
                if(this.dfu_data_blocknum > this.dfu_data_blocklen) {
                    //Éý¼¶³É¹¦
                    this.dfu_wr_stat = DFU_STATE_CHECK_OK;
                    this.dfu_en = DFU_En_Success;
                    this.error_code = Error_Code_Null;
                    break;
                }                
                
                if(this.comm_error_count > 5) {
                   //ͨÐų¬Ê±
                   this.dfu_en = DFU_En_Error;
                   this.error_code = Error_Code_TimeOut;
                   logger.error("DevId:"+dev_id+" ErrorCount:"+comm_error_count+" Stop Update ...");
                   break;
               }
                
                FGCD_Task_Thread_SQL.updateFbs9100S_DFU_StatDataByDev_Id(pool, this);
            }            
        } catch (InterruptedException | IOException e) {
            logger.error(e.toString(),e);
        } finally {
            if(this.dfu_en == DFU_En_Success) {
                logger.info("DevID:" + this.dev_id + " System Update Success .....");
                isSuccess = true;
            }else {
                isSuccess = false;
                logger.info("DevID:" + this.dev_id + " System Update Error .....ErrorCode:" + this.error_code);
            }
            FGCD_Task_Thread_SQL.updateFbs9100S_DFU_StatByDev_Id(pool, this);
        }    
        return isSuccess;
    }
    
    /**
      * ÏòÖ¸¶¨µÄsocketͨµÀ·¢ËÍÊý¾Ý½çÃæÍ¬²½ÇëÇó 
      * @param cmd            ¶ÁȡָÁî
      * @param file_index    Îļþ×ܳ¤¶È
      * @param rec_index    ·¢ËÍË÷Òý
      * @return
      */
   public boolean SocketComm(int cmd,int file_index,int send_index,Socket socket,byte[] bf)
   {
       boolean res_t = false;
       InputStream in = null;
       OutputStream out = null;
       try
       {
           if(null != socket && !socket.isClosed())
           {
               in = socket.getInputStream();
               out = 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,file_index,send_index,bf);
               Date d1 = new Date();
               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() >= 18) && (rx_read_time_out>10)){
                           //    res = true;
                           break;
                       }
                       if(rx_read_time_out > 300) {
                           break;
                       }
                   }
                   Thread.sleep(10);
               }
               Date d2 = new Date();
               long comm_tms = (d2.getTime() - d1.getTime());
               if(comm_tms < 200) {
                   Thread.sleep(200 - comm_tms);
               }
 
               bytebuffer_for_socket_RX.flip();
 
               byte[] cipher_buf = new byte[bytebuffer_for_socket_RX.limit()];
               bytebuffer_for_socket_RX.get(cipher_buf);
               
               //sysState.makeDevCommDataFlowSum(cipher_buf.length);
               
               //System.out.println("Êý¾Ý³¤¶È"+cipher_buf.length+"\t·µ»ØÊý¾Ý£º"+ ComFn.bytesToHexString(cipher_buf, cipher_buf.length));
               if(true == getDataFromCommBuf(cipher_buf)) {
                       res_t = true;                       
               } else {                       
                       res_t = false;
               }
           }
       } catch (IOException | InterruptedException e) {
           logger.error(e.toString(),e);
       } finally {
           if(res_t) {
               comm_error_count = 0;
           }else {
               comm_error_count ++;
           }
       }
       return res_t;
   }
   
   public Boolean getDataFromCommBuf(final byte[] bytes)
   {
       boolean isSuccess = false;
       ByteBuffer bf = ByteBuffer.allocate(bytes.length);
       bf.order(ByteOrder.LITTLE_ENDIAN);
       bf.put(bytes);
       bf.flip();
 
       if(true == m_FBS_Cmd.putByteBuffer(bf))
       {
           //---------------------  ÐÄÌø°ü²âÊÔ    ----------------------------------
           if(FGCD_ComBase.CMD_STARTSysUpdate == m_FBS_Cmd.CMD) {
               if(FGCD_ComBase.RETURN_SUCCESS == m_FBS_Cmd.RecState) {  
                   logger.info("DevId:"+dev_id+" ·¢ËÍ¿ªÊ¼Éý¼¶³É¹¦ ");
                   start_ok = true;
                   isSuccess = true;
               }
           }else if(FGCD_ComBase.CMD_SendUpdateFile == m_FBS_Cmd.CMD) {
               if(FGCD_ComBase.RETURN_SUCCESS == m_FBS_Cmd.RecState) {  
                  int total_dfu_count = m_FBS_Cmd.Db1*256 + m_FBS_Cmd.Db2;
                  this.DataBlockNum = m_FBS_Cmd.Db3*256 + m_FBS_Cmd.Db4;
                  
                  if((DataBlockNum+1) == this.dfu_data_blocknum) {
                      //logger.info("DevId:"+dev_id+"·¢Ë͵Ú"+(DataBlockNum+1)+"/"+total_dfu_count+"Êý¾Ý°ü³É¹¦");
                      //µ±Ç°·¢ËÍÎļþ³É¹¦
                      this.dfu_data_blocknum += 1;
                  }
                  isSuccess = true;
               }
           }         
       }
       return isSuccess;
   }
   
   
   public byte[] makeCommBuf(final int cmd,int file_index, int rec_index,byte[] bf)
   {
        FGCD_Cmd m_cmd = new FGCD_Cmd();
        m_cmd.CMD = cmd;
        m_cmd.Db2     = file_index%256;
        m_cmd.Db1     = file_index/256;
        
        m_cmd.Db4     = rec_index%256;
        m_cmd.Db3 = rec_index/256;
        ByteBuffer bb = ByteBuffer.allocate(0);
        if(bf.length > 0) {
            bb = ByteBuffer.allocate(bf.length + 2);
            bb.order(ByteOrder.LITTLE_ENDIAN);
            bb.put(bf);
            int CRC = FGCD_Crc16.CalCRC16(bb, bf.length);
            bb.putShort(FGCD_ComBase.changeIntToShort(CRC));
        }
        ByteBuffer bbf = FGCD_ComBuf.makeFbs9100CommBuf(m_cmd,bb);
        byte byte_rest[] = new byte[bbf.limit()];
        
        bbf.get(byte_rest);
        return byte_rest;
   }
   
    
    
    public int getDev_id() {
        return dev_id;
    }
 
    public String getDfu_file() {
        return dfu_file;
    }
 
    public int isDfu_en() {
        return dfu_en;
    }
 
    public int getDfu_wr_stat() {
        return dfu_wr_stat;
    }
 
    public int getDfu_data_blocknum() {
        return dfu_data_blocknum;
    }
 
    public int getDfu_data_blocklen() {
        return dfu_data_blocklen;
    }
 
    public String getDfu_password() {
        return dfu_password;
    }
 
    public int getDfu_file_len() {
        return dfu_file_len;
    }
 
    public void setDev_id(int dev_id) {
        this.dev_id = dev_id;
    }
 
    public void setDfu_file(String dfu_file) {
        this.dfu_file = dfu_file;
    }
 
    public void setDfu_en(int dfu_en) {
        this.dfu_en = dfu_en;
    }
 
    public void setDfu_wr_stat(int dfu_wr_stat) {
        this.dfu_wr_stat = dfu_wr_stat;
    }
 
    public void setDfu_data_blocknum(int dfu_data_blocknum) {
        this.dfu_data_blocknum = dfu_data_blocknum;
    }
 
    public void setDfu_data_blocklen(int dfu_data_blocklen) {
        this.dfu_data_blocklen = dfu_data_blocklen;
    }
 
    public void setDfu_password(String dfu_password) {
        this.dfu_password = dfu_password;
    }
 
    public void setDfu_file_len(int dfu_file_len) {
        this.dfu_file_len = dfu_file_len;
    }
 
    @Override
    public String toString() {
        return "FGCD_DFU_State [dev_id=" + dev_id + ", dfu_file=" + dfu_file + ", dfu_en=" + dfu_en + ", dfu_wr_stat="
                + dfu_wr_stat + ", dfu_data_blocknum=" + dfu_data_blocknum + ", dfu_data_blocklen=" + dfu_data_blocklen
                + ", dfu_password=" + dfu_password + ", dfu_file_len=" + dfu_file_len + "]";
    }
 
}