mxpopstar
2022-05-03 e75ef5f04f61aa5fbd89fd5c413dcee1819b7a91
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
package com.dev.fbs9600_zdhj;
import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;
 
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Date;
import java.util.Enumeration;
 
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
 
import com.Com;
import com.Crc16;
import com.PlaySound;
 
public class SPCommZDHJ_9800 implements Runnable/*, SerialPortEventListener*/ {
 
    public static final byte MODBUS_TYPE_YC = 0x01;
    public static final byte MODBUS_TYPE_STD = 0x02;
    
    public static final short CMD_TYPE_READ = 0x03;
    
    public static final short CMD_TYPE_WRITE_YC = 0x05;
    public static final short CMD_TYPE_WRITE_STD = 0x06;
    public static final short CMD_TYPE_WRITE_MULTY = 0x10;
    
    public static final int DEV_PARAM_DATA_STATE_NULL = 0;
    public static final int DEV_PARAM_DATA_STATE_QUERY = 1;
    public static final int DEV_PARAM_DATA_STATE_UPDATE = 2;
    
    public static final int ZDHJ_MON_COUNT_MAX = 300;
    public static final int ZDHJ_MON_CHANNEL_MAX = 4;
 
    public static final int ZDHJ_PARAM_RegAddr_Start = 0x1001;
    public static final int ZDHJ_PARAM_RegAddr_End = 0x1000 + 25;
    
    public static final int ZDHJ_GroupData_RegAddr_Start = 0x2001;
    public static final int ZDHJ_GroupData_RegAddr_End = (ZDHJ_GroupData_RegAddr_Start - 1) + 10;
    
    public static final int ZDHJ_MonVol_RegAddr_Start = ZDHJ_GroupData_RegAddr_End + 1;
    public static final int ZDHJ_MonVol_RegAddr_End = (ZDHJ_MonVol_RegAddr_Start - 1) + ZDHJ_MON_COUNT_MAX*2;
    
    public static final int ZDHJ_MonTmp_RegAddr_Start = ZDHJ_MonVol_RegAddr_End + 1;
    public static final int ZDHJ_MonTmp_RegAddr_End = (ZDHJ_MonTmp_RegAddr_Start - 1) + ZDHJ_MON_COUNT_MAX*2;
    
    public static final int ZDHJ_MonRes_RegAddr_Start = ZDHJ_MonTmp_RegAddr_End + 1;
    public static final int ZDHJ_MonRes_RegAddr_End = (ZDHJ_MonRes_RegAddr_Start - 1) + ZDHJ_MON_COUNT_MAX*2;
    
    public static final int ZDHJ_ResTest_Start_RegAddr = 0x4001;    //Æô¶¯ÄÚ×è²âÊÔ
    public static final int ZDHJ_ResTest_Stop_RegAddr = 0x4002;        //Í£Ö¹ÄÚ×è²âÊÔ
    public static final int ZDHJ_ResStart_System_RegAddr = 0x4003;    //ÖØÆôÉ豸
    public static final int ZDHJ_SetCurrZero_RegAddr = 0x4004;        //ÉèÖõçÁ÷Áãµã
    public static final int ZDHJ_AdjCurrSlope_RegAddr = 0x4005;        //У׼µçÁ÷бÂÊ
    public static final int ZDHJ_AdjVolOffset_RegAddr = 0x4006;        //У׼µçÑ¹Æ«ÒÆÁ¿
    public static final int ZDHJ_AdjVolSlope_RegAddr = 0x4007;        //У׼µçѹϵÊý
    
    public static final int ZDHJ_OP_NULL_ACK = 0;
    public static final int ZDHJ_OP_READ_PARAM_OK = 1;
    public static final int ZDHJ_OP_READ_PARAM_FAILED = 2;
    public static final int ZDHJ_OP_WRITE_PARAM_OK = 3;
    public static final int ZDHJ_OP_WRITE_PARAM_FAILED = 4;
    
    public static final int ZDHJ_OP_START_RES_OK = 5;
    public static final int ZDHJ_OP_START_RES_FAILED = 6;
    public static final int ZDHJ_OP_STOP_RES_OK = 7;
    public static final int ZDHJ_OP_STOP_RES_FAILED = 8;
    
    public static final int ZDHJ_OP_SetCurrZero_OK = 9;
    public static final int ZDHJ_OP_SetCurrZero_FAILED = 10;
    public static final int ZDHJ_OP_SetCurrSlope_OK = 11;
    public static final int ZDHJ_OP_SetCurrSlope_FAILED = 12;
    
    public static final int ZDHJ_OP_SetVolSlope_OK = 13;
    public static final int ZDHJ_OP_SetVolSlope_FAILED = 14;
    
    public static final int ZDHJ_OP_RestartDev_OK = 15;
    public static final int ZDHJ_OP_RestartDev_FAILED = 16;
    /*********************************************************************/
    final public static String[] ZDHJ_OP_REST_INF_TEXT = new String[] {
            "ÎÞ²Ù×÷",
            "¶ÁÈ¡²ÎÊý³É¹¦!",
            "¶ÁÈ¡²ÎÊýʧ°Ü!!!!!!!!!!",
            "ÉèÖòÎÊý³É¹¦!",
            "ÉèÖòÎÊýʧ°Ü!!!!!!!!!!",
            "Æô¶¯ÄÚ×è²âÊԳɹ¦!",
            "Æô¶¯ÄÚ×è²âÊÔʧ°Ü!!!!!!!!!",
            "Í£Ö¹ÄÚ×è²âÊԳɹ¦!",
            "Í£Ö¹ÄÚ×è²âÊÔʧ°Ü!!!!!!!!!",
            "ÇåÁãµçÁ÷³É¹¦!",
            "ÇåÁãµçÁ÷ʧ°Ü!!!!!!!!!",
            "ÉèÖõçÁ÷ϵÊý³É¹¦!",
            "ÉèÖõçÁ÷ϵÊýʧ°Ü!!!!!!!!!",
            "ÉèÖõçѹϵÊý³É¹¦!",
            "ÉèÖõçѹϵÊýʧ°Ü!!!!!!!!!",
    };
    
    final public static String[] ZDHJ_OP_REST_INF_TEXT_EN = new String[] {
        "None Op",
        "Read Param Done!",
        "Failed To Read Param!!!!!!!!!!",
        "Write Param Done!",
        "Failed To Write Param!!!!!!!!!",
        "Start Res Test Done!",
        "Failed To Start Res Test!!!!!!!!!",
        "Stop Res Test Done!",
        "Failed To Stop Res Test!!!!!!!!!",
        "Clear Curr Done!",
        "Failed To Clear Curr!!!!!!!!!",
        "Calibrate Curr Done!",
        "Failed To Calibrate Curr!!!!!!!!!",
        "Calibrate Group Vol Done!",
        "Failed To Calibrate Group Vol!!!!",
};
    
    // ¼ì²âϵͳÖпÉÓõÄͨѶ¶Ë¿ÚÀà
    private static CommPortIdentifier portId;
    private static Enumeration<CommPortIdentifier> portList;
    // ÊäÈëÊä³öÁ÷
    public static InputStream inputStream;
    public static OutputStream outputStream;
    // RS-232µÄ´®ÐпÚ
    public static SerialPort serialPort;
    
    public short m_CMD_TYPE_WRITE = CMD_TYPE_WRITE_YC;
    private byte m_MODBUS_TYPE = MODBUS_TYPE_YC;
    
    private  boolean CommThreadRunning = false;
    public  boolean AutoStartResTestEn = false;
    public  int AutoStartResTestType = ZDHJ_ResTest_Start_RegAddr;
    public  Date AutoStartResTestTime = new Date();
    public  Date AutoSaveResDataTime = new Date();
    public  boolean AutoSaveResDataEn = false;
    public  int AutoSaveResDataCount = 0;
    public  String AutoSaveDataFileName = "";
    
    private ByteBuffer CommRxBuffer = ByteBuffer.allocate(1500); 
    private ByteBuffer CommTxBuffer = ByteBuffer.allocate(1048);
    
    private ByteBuffer DFUCommRxBuffer = ByteBuffer.allocate(1048); 
    private ByteBuffer DFUCommTxBuffer = ByteBuffer.allocate(1048);
    
    private ByteBuffer FBS9100TxBuffer = ByteBuffer.allocate(1048);
    private ByteBuffer FBS9100RxBuffer = ByteBuffer.allocate(1500);
    
    public short comm_tx_cnt = 0;
    public short comm_rx_cnt = 0;
    
    private int comm_bautrate = 9600;
    public int dt_target_addr = 0;
    public int m_ZDHJ_REG_ADDR = ZDHJ_PARAM_RegAddr_Start;
    public int m_ZDHJ_REG_CNT = 1;
    public int ZDHJ_BattCount = -1;
    //--------------------------------------------------------//
    public int dev_param_data_state = 0;
    public int dev_param_addr = 0;
    public int[] dev_param_ch_mon_cnt = new int[ZDHJ_MON_CHANNEL_MAX];
    public int dev_param_curr_range = 0;
    public double dev_param_FloatCurrLev = 0;
    public double dev_param_float_curr_lev = 0;
    public double dev_param_wenbo_curr_lev = 0;
    public int dev_param_auto_restest_interval = 0;
    public int dev_param_res_test_type = 0;
    public int dev_param_ResDisTestMethod = 0;
    public int dev_param_Batt_StdCap = 0;
    public double dev_param_res_dis_slope = 0;
    public double dev_param_res_wenbo_slope = 0;
    public int dev_param_monnum_setmode = 0;
    //--------------------------------------------------------//
    public double dev_stat_version = 0;
    public int dev_stat_state = 0;
    public double GroupVol = 0;
    public double BattCurr = 0;
    public int BattState = 0;
    public int BattCurrDir = 0;
    public double AvgWenBoCurr = 0;
    public double PeakWenBoCurr = 0;
    public int[] MonCommErrCount = new int[ZDHJ_MON_CHANNEL_MAX];     //RS485µ¥ÌåͨµÀͨÐÅ´íÎó¼ÆÊý
    public int SpiCommErrCount = 0;                                      //SPIͨÐÅ´íÎó¼ÆÊý
    public int ResTestCount = 0;                                     //ÄÚ×è²âÊÔ´ÎÊý
    public int CurentResTestMode = 0;                                 //µ±Ç°ÄÚ×è²âÊÔ·½·¨
    public double[] monVol = new double[ZDHJ_MON_COUNT_MAX];
    public int[] monVolAlarm = new int[ZDHJ_MON_COUNT_MAX];
    public double[] monTmp = new double[ZDHJ_MON_COUNT_MAX];
    public int[] monTmpAlarm = new int[ZDHJ_MON_COUNT_MAX];
    public double[] monRes = new double[ZDHJ_MON_COUNT_MAX];
    public int[] monResAlarm = new int[ZDHJ_MON_COUNT_MAX];
    //--------------------------------------------------------//
    public short mAddrSettedNow = 0;
    
    private short dt_cmd = CMD_TYPE_READ;
    public int dt_cmd_ack = ZDHJ_OP_NULL_ACK;
    public Date dt_cmd_ack_time = new Date();
    private short dt_cmd_regaddr = 0;
    private short dt_cmd_regcnt = 0;
    private short[] dt_cmd_regdata = null;
    
    public SPCommZDHJ_9800(short addr_t, int bitrate) {
        dt_target_addr = addr_t & 0x00FF;
        comm_bautrate = bitrate;
    }
    
    public static void searchCommPort(JComboBox<String> cb_comm) {
        cb_comm.removeAllItems();
        @SuppressWarnings("unchecked")
        Enumeration<CommPortIdentifier> pl = CommPortIdentifier.getPortIdentifiers();
        while (pl.hasMoreElements()) {
            CommPortIdentifier port_id = pl.nextElement();
            if (port_id.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                cb_comm.addItem(port_id.getName());
            }
        }
    }
    
    public void setCommBautrate(int bt_rate) {
        try {
            comm_bautrate = bt_rate;
            serialPort.setSerialPortParams(comm_bautrate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
        } catch (UnsupportedCommOperationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    //³õʼ»¯´®¿Ú
    @SuppressWarnings("unchecked")
    public boolean OpenCommPort(String comm_name) {
        portList = CommPortIdentifier.getPortIdentifiers();
        while (portList.hasMoreElements()) {
            portId = portList.nextElement();
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                if (portId.getName().equals(comm_name)) {
                    try {
                        serialPort = (SerialPort) portId.open("SerialPort-Test", 2000);
                        //serialPort.addEventListener(new SPComm());
                        serialPort.notifyOnDataAvailable(true);
                        /* ÉèÖô®¿ÚͨѶ²ÎÊý */
                        serialPort.setSerialPortParams(comm_bautrate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
                        
                        outputStream = serialPort.getOutputStream();
                        inputStream = serialPort.getInputStream();
                    } catch (PortInUseException e) {
                        e.printStackTrace();
                    }/* catch (TooManyListenersException e) {
                        e.printStackTrace();
                    }*/catch (UnsupportedCommOperationException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } 
                }
            }
        }
        if(null == serialPort) {
            System.out.println(comm_name + "²»´æÔÚ»òÕýÔÚʹÓÃÖÐ!");
            return false;
        } else {
            CommTxBuffer.order(ByteOrder.BIG_ENDIAN);
            CommRxBuffer.order(ByteOrder.BIG_ENDIAN);
            DFUCommTxBuffer.order(ByteOrder.LITTLE_ENDIAN);
            DFUCommRxBuffer.order(ByteOrder.LITTLE_ENDIAN);
            FBS9100TxBuffer.order(ByteOrder.LITTLE_ENDIAN);
            FBS9100RxBuffer.order(ByteOrder.LITTLE_ENDIAN);
            comm_tx_cnt = 0;
            comm_rx_cnt = 0;
            CommThreadRunning = true;
            return true;
        }
    }
    
    private void makeCommTxData() {
        CommTxBuffer.clear();
        short dt_cmd_tmp = dt_cmd;
        if(CMD_TYPE_READ == dt_cmd_tmp) {
            
            if(dt_cmd_regaddr > 0) {
                m_ZDHJ_REG_ADDR = dt_cmd_regaddr;
                m_ZDHJ_REG_CNT = 0;
                dt_cmd_regaddr = 0;
            }
            
            if((ZDHJ_BattCount<0) || (0==m_ZDHJ_REG_ADDR) || (ZDHJ_PARAM_RegAddr_Start==m_ZDHJ_REG_ADDR)) {
                m_ZDHJ_REG_ADDR = ZDHJ_PARAM_RegAddr_Start;
                m_ZDHJ_REG_CNT = (ZDHJ_PARAM_RegAddr_End-ZDHJ_PARAM_RegAddr_Start) + 1;
            } else {
                m_ZDHJ_REG_ADDR += m_ZDHJ_REG_CNT;
                m_ZDHJ_REG_CNT = ZDHJ_BattCount;
                
                if((m_ZDHJ_REG_ADDR >= ZDHJ_GroupData_RegAddr_Start) && (m_ZDHJ_REG_ADDR < ZDHJ_GroupData_RegAddr_End)) {
                    if(m_ZDHJ_REG_ADDR <= ZDHJ_GroupData_RegAddr_Start) {
                        m_ZDHJ_REG_ADDR = ZDHJ_GroupData_RegAddr_Start;
                        m_ZDHJ_REG_CNT = (ZDHJ_GroupData_RegAddr_End-ZDHJ_GroupData_RegAddr_Start) + 1;
                    } else {
                        m_ZDHJ_REG_ADDR = ZDHJ_MonVol_RegAddr_Start;
                    }
                }
                
                if((m_ZDHJ_REG_ADDR >= ZDHJ_MonVol_RegAddr_Start) && (m_ZDHJ_REG_ADDR < ZDHJ_MonVol_RegAddr_End)) {
                    if(m_ZDHJ_REG_ADDR < (ZDHJ_MonVol_RegAddr_Start+ZDHJ_BattCount)) {
                        m_ZDHJ_REG_CNT = (ZDHJ_MonVol_RegAddr_Start+ZDHJ_BattCount)-m_ZDHJ_REG_ADDR;
                    } else {
                        m_ZDHJ_REG_ADDR = ZDHJ_MonTmp_RegAddr_Start;
                    }
                }
                
                if((m_ZDHJ_REG_ADDR >= ZDHJ_MonTmp_RegAddr_Start) && (m_ZDHJ_REG_ADDR < ZDHJ_MonTmp_RegAddr_End)) {
                    if(m_ZDHJ_REG_ADDR < (ZDHJ_MonTmp_RegAddr_Start+ZDHJ_BattCount)) {
                        m_ZDHJ_REG_CNT = (ZDHJ_MonTmp_RegAddr_Start+ZDHJ_BattCount)-m_ZDHJ_REG_ADDR;
                    } else {
                        m_ZDHJ_REG_ADDR = ZDHJ_MonRes_RegAddr_Start;
                    }
                }
                
                if((m_ZDHJ_REG_ADDR >= ZDHJ_MonRes_RegAddr_Start) && (m_ZDHJ_REG_ADDR < ZDHJ_MonRes_RegAddr_End)) {
                    if(m_ZDHJ_REG_ADDR < (ZDHJ_MonRes_RegAddr_Start+ZDHJ_BattCount)) {
                        m_ZDHJ_REG_CNT = (ZDHJ_MonRes_RegAddr_Start+ZDHJ_BattCount)-m_ZDHJ_REG_ADDR;
                    } else {
                        m_ZDHJ_REG_ADDR = ZDHJ_GroupData_RegAddr_Start;
                        m_ZDHJ_REG_CNT = (ZDHJ_GroupData_RegAddr_End-ZDHJ_GroupData_RegAddr_Start) + 1;
                    }
                }
                
                if(m_ZDHJ_REG_CNT > 120) {
                    m_ZDHJ_REG_CNT = 120;
                }
            }
            CommTxBuffer.put((byte) dt_target_addr);
            CommTxBuffer.put((byte) dt_cmd_tmp);
            CommTxBuffer.putShort((short) m_ZDHJ_REG_ADDR);
            CommTxBuffer.putShort((short) m_ZDHJ_REG_CNT);
            
            //System.out.println("m_ZDHJ_REG_ADDR:" + m_ZDHJ_REG_ADDR + ", m_ZDHJ_REG_CNT:" + m_ZDHJ_REG_CNT);
        } else if (m_CMD_TYPE_WRITE == dt_cmd_tmp) {
            m_ZDHJ_REG_ADDR = dt_cmd_regaddr;
            m_ZDHJ_REG_CNT = dt_cmd_regcnt;
            
            CommTxBuffer.put((byte) dt_target_addr);
            CommTxBuffer.put((byte) dt_cmd_tmp);
            CommTxBuffer.putShort((short) dt_cmd_regaddr);
            CommTxBuffer.putShort(dt_cmd_regdata[0]);
            /*
            System.out.println("dt_cmd_regaddr:" + m_ZDHJ_REG_ADDR + ", "
                                + "dt_cmd_regdata:" + (dt_cmd_regdata[0]&0xFFFF) + ", "
                                + "dt_cmd_regcnt:" + m_ZDHJ_REG_CNT);
            */
            dt_cmd = CMD_TYPE_READ;
            dt_cmd_regaddr = 0;
        } else if (CMD_TYPE_WRITE_MULTY == dt_cmd_tmp) {
            m_ZDHJ_REG_ADDR = dt_cmd_regaddr;
            m_ZDHJ_REG_CNT = dt_cmd_regcnt;
            
            CommTxBuffer.put((byte) dt_target_addr);
            CommTxBuffer.put((byte) dt_cmd_tmp);
            CommTxBuffer.putShort((short) dt_cmd_regaddr);
            CommTxBuffer.putShort((short) dt_cmd_regcnt);
            CommTxBuffer.put((byte)( m_ZDHJ_REG_CNT*2));
            if(null != dt_cmd_regdata) {
                for(int n=0; n<dt_cmd_regcnt; n++) {
                    CommTxBuffer.putShort(dt_cmd_regdata[n]);
                }
            }
            /*
            System.out.println("dt_cmd_regaddr:" + m_ZDHJ_REG_ADDR + ", "
                                + "dt_cmd_regdata:" + (dt_cmd_regdata[0]&0xFFFF) + ", "
                                + "dt_cmd_regcnt:" + m_ZDHJ_REG_CNT);
            */
            dt_cmd = CMD_TYPE_READ;
            dt_cmd_regaddr = 0;
        }
        
        int crc = Crc16.CalCRC16(CommTxBuffer, CommTxBuffer.position()) & 0xFFFF;
        if(MODBUS_TYPE_STD == m_MODBUS_TYPE) {
            CommTxBuffer.putShort((short) crc);
        } else {
            CommTxBuffer.putShort((short) (crc>>8 | crc<<8));
        }
        
        CommTxBuffer.flip();
    }
    
    //Ïò´®¿Ú·¢ËÍÐÅÏ¢·½·¨
    public void sendMsg(ByteBuffer bbf_tx) throws IOException {
        byte[] bt_t = new byte[bbf_tx.limit()];
        bbf_tx.get(bt_t);
        
        //System.out.println(ComFn.bytesToHexString(bt_t, bt_t.length));
        
        outputStream.write(bt_t);
        if(++comm_tx_cnt > 32500) {
            comm_tx_cnt = 0;
        }
    }
    
    public void readMsg(ByteBuffer bbf_rx) throws IOException, InterruptedException {
        bbf_rx.clear();
        int time_out = 0;
        byte[] rx_buf_t = new byte[280];
        while(true) {
            if(inputStream.available() > 0) {
                time_out = 0;
                int rx_cnt_t = inputStream.read(rx_buf_t);
                if((bbf_rx.position()+rx_cnt_t) < (bbf_rx.capacity()-1)) {
                    bbf_rx.put(rx_buf_t, 0, rx_cnt_t);
                } else {
                    break;
                }
            } else {
                Thread.sleep(10);
                time_out++;
                if(0 == bbf_rx.position()) {
                    if(time_out > 200) {
                        break;
                    }
                } else {
                    if(time_out > 4) {
                        break;
                    }
                }
            }
        }
        bbf_rx.flip();
        /*
        byte[] bt_t_rx = new byte[bbf_rx.limit()];
        bbf_rx.get(bt_t_rx);
        System.out.println(ComFn.bytesToHexString(bt_t_rx, bt_t_rx.length));
        */
    }
    
    public void CloseCommPort() {
        CommThreadRunning = false;
    }
    
    public void setCommCmd(short cmd, int cmd_reg_addr, short[] reg_data, int reg_len) {
        if(dt_cmd_regaddr > 0) {
            return;
        }
        
        dt_cmd = cmd;
        dt_cmd_regaddr = (short) cmd_reg_addr;
        dt_cmd_regdata = reg_data;
        dt_cmd_regcnt = (short) reg_len;
    }
    
    public void setCommCmdAck(int ack_t) {
        dt_cmd_ack = ack_t;
        dt_cmd_ack_time = new Date();
        //System.out.println(Com.get_DTF(dt_cmd_ack_time, Com.DTF_YMDhms) + ", " + dev_param_data_state);
        String wav_f = "6133.wav";
        if(ack_t%2 == 0) {
            wav_f = "4577.wav";
        }
        if(ack_t > 0) {
            new PlaySound(wav_f);
        }
    }
    
    private boolean checkCommBuf(ByteBuffer buf_t) {
        boolean res = false;
        if(buf_t.limit() > 4) {
            /*************************************************/
            buf_t.position(buf_t.limit() - 2);
            int crc = buf_t.getShort() & 0xFFFF;
            /*************************************************/
            buf_t.position(0);
            int crc_cal = Crc16.CalCRC16(buf_t, buf_t.limit()-2) & 0xFFFF;
            //crc_cal = (short)((crc_cal>>8) | (crc_cal<<8)) & 0xFFFF;
            /*************************************************/
            buf_t.position(0);
            /*************************************************/
            if(MODBUS_TYPE_STD == m_MODBUS_TYPE) {
                if(crc_cal == crc) {
                    res = true;
                } 
                /*
                if(true == res) {
                    m_MODBUS_TYPE = MODBUS_TYPE_STD;
                    m_CMD_TYPE_WRITE = CMD_TYPE_WRITE_STD;
                } else {
                    m_MODBUS_TYPE = MODBUS_TYPE_YC;
                    m_CMD_TYPE_WRITE = CMD_TYPE_WRITE_YC;
                }
                */
            } else {
                crc_cal = (short)((crc_cal>>8) | (crc_cal<<8)) & 0xFFFF;
                if(crc_cal == crc) {
                    res = true;
                } 
                /*
                if(true == res) {
                    m_MODBUS_TYPE = CMD_TYPE_WRITE_YC;
                    m_CMD_TYPE_WRITE = CMD_TYPE_WRITE_YC;
                } else {
                    m_MODBUS_TYPE = CMD_TYPE_WRITE_STD;
                    m_CMD_TYPE_WRITE = CMD_TYPE_WRITE_STD;
                }
                */
            }
            /*************************************************/
        } else {
            if(MODBUS_TYPE_STD == m_MODBUS_TYPE) {
                m_MODBUS_TYPE = MODBUS_TYPE_YC;
                m_CMD_TYPE_WRITE = CMD_TYPE_WRITE_YC;
            } else {
                m_MODBUS_TYPE = MODBUS_TYPE_STD;
                m_CMD_TYPE_WRITE = CMD_TYPE_WRITE_STD;
            }
        }
        
        return res;
    }
    
    private void processRxData(ByteBuffer bbf_rx, int reg_addr_t, int reg_count) {
        //if(bbf_rx.limit() > 5) 
        {
            
            if(false == checkCommBuf(bbf_rx)) {
                //System.out.println("processRxData crc_err, bbf_rx.limit(): " + bbf_rx.limit());
                return;
            }
            
            bbf_rx.position(0);
            bbf_rx.get();
            byte op_cmd_t = bbf_rx.get();
            //short reg_addr_t = bbf_rx.getShort();
            
            if(CMD_TYPE_WRITE_MULTY == op_cmd_t) {
                bbf_rx.position(4);
                  int res_t = bbf_rx.getShort();
                if((reg_addr_t >= ZDHJ_PARAM_RegAddr_Start) && (reg_addr_t < ZDHJ_PARAM_RegAddr_End)) {
                    if(1 == res_t) {
                         setCommCmdAck(SPCommZDHJ_9800.ZDHJ_OP_WRITE_PARAM_OK);
                     } else {
                         setCommCmdAck(SPCommZDHJ_9800.ZDHJ_OP_WRITE_PARAM_FAILED);
                     }
                }
             } else if(m_CMD_TYPE_WRITE == op_cmd_t) {
                bbf_rx.position(4);
                int res_t = bbf_rx.getShort();
                
                if(ZDHJ_ResTest_Start_RegAddr == reg_addr_t) {
                    if(1 == res_t) {
                        setCommCmdAck(SPCommZDHJ_9800.ZDHJ_OP_START_RES_OK);
                    } else {
                        setCommCmdAck(SPCommZDHJ_9800.ZDHJ_OP_START_RES_FAILED);
                    }
                }
                if(ZDHJ_ResTest_Stop_RegAddr == reg_addr_t) {
                    if(1 == res_t) {
                        setCommCmdAck(SPCommZDHJ_9800.ZDHJ_OP_STOP_RES_OK);
                    } else {
                        setCommCmdAck(SPCommZDHJ_9800.ZDHJ_OP_STOP_RES_FAILED);
                    }
                }
                if(ZDHJ_SetCurrZero_RegAddr == reg_addr_t) {
                    if(1 == res_t) {
                        setCommCmdAck(SPCommZDHJ_9800.ZDHJ_OP_SetCurrZero_OK);
                    } else {
                        setCommCmdAck(SPCommZDHJ_9800.ZDHJ_OP_SetCurrZero_FAILED);
                    }
                }
                if(ZDHJ_AdjCurrSlope_RegAddr == reg_addr_t) {
                    if(1 == res_t) {
                        setCommCmdAck(SPCommZDHJ_9800.ZDHJ_OP_SetCurrSlope_OK);
                    } else {
                        setCommCmdAck(SPCommZDHJ_9800.ZDHJ_OP_SetCurrSlope_FAILED);
                    }
                }
                if(ZDHJ_AdjVolSlope_RegAddr == reg_addr_t) {
                    if(1 == res_t) {
                        setCommCmdAck(SPCommZDHJ_9800.ZDHJ_OP_SetVolSlope_OK);
                    } else {
                        setCommCmdAck(SPCommZDHJ_9800.ZDHJ_OP_SetVolSlope_FAILED);
                    }
                }
                if(ZDHJ_ResStart_System_RegAddr == reg_addr_t) {
                    if(1 == res_t) {
                        setCommCmdAck(SPCommZDHJ_9800.ZDHJ_OP_RestartDev_OK);
                    } else {
                        setCommCmdAck(SPCommZDHJ_9800.ZDHJ_OP_RestartDev_FAILED);
                    }
                }
            } else if(CMD_TYPE_READ == op_cmd_t) {
                bbf_rx.position(3);
                if((reg_addr_t >= ZDHJ_PARAM_RegAddr_Start) && (reg_addr_t < ZDHJ_PARAM_RegAddr_End)) {
                    dev_param_addr = bbf_rx.getShort();
                    
                    int mon_cnt_t = 0;
                    for(int n=0; n<dev_param_ch_mon_cnt.length; n++) {
                        dev_param_ch_mon_cnt[n] = bbf_rx.getShort();
                        mon_cnt_t += dev_param_ch_mon_cnt[n];
                    }
                    ZDHJ_BattCount = mon_cnt_t;
                    
                    dev_param_curr_range = bbf_rx.getShort();
                    dev_param_FloatCurrLev = ((double)bbf_rx.getShort()) / 10;
                    dev_param_wenbo_curr_lev = ((double)bbf_rx.getShort()) / 100;
                    dev_param_auto_restest_interval = bbf_rx.getShort();
                    dev_param_res_test_type = bbf_rx.getShort();
                    dev_param_ResDisTestMethod = bbf_rx.getShort();
                    dev_param_Batt_StdCap = bbf_rx.getShort();
                    dev_param_res_dis_slope = ((double)bbf_rx.getShort()) / 10000;
                    dev_param_res_wenbo_slope = ((double)bbf_rx.getShort()) / 10000;
                    dev_param_monnum_setmode = bbf_rx.getShort();
                    
                    dev_param_data_state = DEV_PARAM_DATA_STATE_UPDATE;
                    setCommCmdAck(SPCommZDHJ_9800.ZDHJ_OP_READ_PARAM_OK);
                }
                if((reg_addr_t >= ZDHJ_GroupData_RegAddr_Start) && (reg_addr_t < ZDHJ_GroupData_RegAddr_End)) {
                    dev_stat_version = ((double)bbf_rx.getShort()) / 10;
                    dev_stat_state = bbf_rx.getShort();
                    
                    GroupVol = ((double)bbf_rx.getShort()) / 10;
                    BattCurr = ((double)bbf_rx.getShort()) / 10;
                    BattState = bbf_rx.getShort();
                    BattCurrDir = (byte) bbf_rx.getShort();
                    AvgWenBoCurr = ((double)bbf_rx.getShort()) / 100;
                    PeakWenBoCurr = ((double)bbf_rx.getShort()) / 100;
                    for(int n=0; n<ZDHJ_MON_CHANNEL_MAX; n++) {
                        MonCommErrCount[n] = bbf_rx.getShort();
                    }
                    SpiCommErrCount = bbf_rx.getShort();
                    ResTestCount = bbf_rx.getShort();
                    CurentResTestMode = bbf_rx.getShort();
                }
                if((reg_addr_t >= ZDHJ_MonVol_RegAddr_Start) && (reg_addr_t < ZDHJ_MonVol_RegAddr_End)) {
                    for(int n=0; n<reg_count; n++) {
                        monVol[reg_addr_t-ZDHJ_MonVol_RegAddr_Start+(n/2)] = ((double)bbf_rx.getShort()) / 1000;
                        monVolAlarm[reg_addr_t-ZDHJ_MonVol_RegAddr_Start+(n/2)] = bbf_rx.getShort();
                        n++;
                    }
                }
                if((reg_addr_t >= ZDHJ_MonTmp_RegAddr_Start) && (reg_addr_t < ZDHJ_MonTmp_RegAddr_End)) {
                    for(int n=0; n<reg_count; n++) {
                        monTmp[reg_addr_t-ZDHJ_MonTmp_RegAddr_Start+(n/2)] = ((double)bbf_rx.getShort()) / 10 - 10.0;
                        monTmpAlarm[reg_addr_t-ZDHJ_MonTmp_RegAddr_Start+(n/2)] = bbf_rx.getShort();
                        n++;
                    }
                }
                if((reg_addr_t >= ZDHJ_MonRes_RegAddr_Start) && (reg_addr_t < ZDHJ_MonRes_RegAddr_End)) {
                    for(int n=0; n<reg_count; n++) {
                        monRes[reg_addr_t-ZDHJ_MonRes_RegAddr_Start+(n/2)] = ((double)bbf_rx.getShort()) / 1000;
                        monResAlarm[reg_addr_t-ZDHJ_MonRes_RegAddr_Start+(n/2)] = bbf_rx.getShort();
                        n++;
                    }
                }
            }
            
            if(++comm_rx_cnt > 32500) {
                comm_rx_cnt = 0;
            }
        }
    }
    
    public void setAutoStartRestTest(String filename, int type, boolean en) {
        AutoSaveDataFileName = filename;
        AutoStartResTestType = type;
        AutoStartResTestEn = en;
        AutoSaveResDataCount = 0;
    }
    
    public void run() {
        while(true == CommThreadRunning) {
            try {
                makeCommTxData();
                sendMsg(CommTxBuffer);
                readMsg(CommRxBuffer);
                /*
                byte[] tmp = new byte[CommRxBuffer.limit()];
                CommRxBuffer.get(tmp);
                System.out.println(ComFn.bytesToHexString(tmp, tmp.length));
                */
                processRxData(CommRxBuffer, m_ZDHJ_REG_ADDR, m_ZDHJ_REG_CNT);
                if((ZDHJ_PARAM_RegAddr_Start == m_ZDHJ_REG_ADDR)
                    || (ZDHJ_ResTest_Start_RegAddr == m_ZDHJ_REG_ADDR)
                    || (ZDHJ_ResTest_Stop_RegAddr == m_ZDHJ_REG_ADDR)
                    || (ZDHJ_ResStart_System_RegAddr == m_ZDHJ_REG_ADDR)
                    || (ZDHJ_SetCurrZero_RegAddr == m_ZDHJ_REG_ADDR)
                    || (ZDHJ_AdjCurrSlope_RegAddr == m_ZDHJ_REG_ADDR)
                    || (ZDHJ_AdjVolOffset_RegAddr == m_ZDHJ_REG_ADDR)
                    || (ZDHJ_AdjVolSlope_RegAddr == m_ZDHJ_REG_ADDR)) {
                    m_ZDHJ_REG_ADDR = ZDHJ_GroupData_RegAddr_Start;
                    m_ZDHJ_REG_CNT = 0;
                }
                Thread.sleep(200);
                
                if(true == AutoStartResTestEn) {
                    if((new Date().getTime() - AutoStartResTestTime.getTime())/1000 > 60) {
                        /*
                        short[] res_type_tag = new short[1];
                        res_type_tag[0] = 0x0000;
                        this.setCommCmd(SPCommZDHJ.CMD_TYPE_WRITE, AutoStartResTestType, 
                                                    res_type_tag, res_type_tag.length);
                        */
                        AutoStartResTestTime = new Date();
                        AutoSaveResDataEn = true;
                    }
                    
                    if(true == AutoSaveResDataEn) {
                        if((new Date().getTime() - AutoStartResTestTime.getTime())/1000 > 15) {
                            AutoSaveResDataEn = false;
                            try {
                                String temp = Com.get_DTF(new Date(), Com.DTF_YMDhms) + ",";
                                for(int c=0; c<ZDHJ_BattCount; c++) {
                                    temp += String.format("%1.3f,", monVol[c]);
                                }
                                for(int c=0; c<ZDHJ_BattCount; c++) {
                                    temp += String.format("%1.1f,", monTmp[c]);
                                }
                                for(int c=0; c<ZDHJ_BattCount; c++) {
                                    temp += String.format("%1.3f,", monRes[c]);
                                }
                                temp += "\n";
                                
                                FileWriter fw = new FileWriter(AutoSaveDataFileName, true);
                                fw.write(temp.toCharArray());
                                fw.close();
                                AutoSaveResDataTime = new Date();
                                AutoSaveResDataCount += 1;
                            } catch(Exception e) {
                                  e.printStackTrace();
                            }
                        }
                    }
                }
            } catch (InterruptedException | IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                CloseCommPort();
                JOptionPane.showMessageDialog(null, "ZDHJ CommPort ´®¿ÚÒì³£: " + e.getMessage());
            }
        }
        /******************************************/
        serialPort.close();
        /******************************************/
        System.out.println("ZDHJ CommPort is quit!");
    }
}