package org.ts.ddcs.Controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.ts.ddcs.Config.ServerConfig;
import org.ts.ddcs.DataItemTemplate.DataItemTemplateInterface;
import org.ts.ddcs.DataTemplate.*;
import org.ts.ddcs.Entity.*;
import org.ts.ddcs.Log.LogHelper;
import org.ts.ddcs.Service.SwService;
import org.ts.ddcs.Service.WqService;
import org.ts.ddcs.Tool.BytesHelp;
import org.ts.ddcs.Tool.IForestCheckHelp;
import org.ts.ddcs.Worker.DataProcess;
import org.ts.ddcs.Worker.DataProcessHolder;
import org.ts.ddcs.WxController.service.WxService;
import org.ts.ddcs.utils.GBConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;


import java.io.*;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class ManageClientController {

    @Autowired
    private ServerConfig config;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private WxService wxService;


    @GetMapping(value = "DataCollectServer/Manage/mqtt/{rtucode}")
    public Object mqtt(@PathVariable(name = "rtucode") String rtucode) {
        JSONObject info = new JSONObject();
        info.put("msg_code", "online_rtu_num");

        info.put("name", "在线数量");
        info.put("value", "562");


        DataProcessHolder.newInstance().dataProcess.mqttServer.send(info.toJSONString());


        info = new JSONObject();
        info.put("msg_code", "datagram_up_num_in_hour");

        info.put("name", "1小时报文上报数量");
        info.put("value", "655555");


        DataProcessHolder.newInstance().dataProcess.mqttServer.send(info.toJSONString());

        info = new JSONObject();
        info.put("msg_code", "datagram_up_peak_value_in_hour");

        info.put("name", "1小时上报峰值");

        JSONArray list = new JSONArray();

        JSONObject d = new JSONObject();
        d.put("name", "5分");
        d.put("value", 25);
        list.add(d);


        d = new JSONObject();
        d.put("name", "10分");
        d.put("value", 90);
        list.add(d);


        d = new JSONObject();
        d.put("name", "15分");
        d.put("value", 9);
        list.add(d);

        info.put("list", list);

        DataProcessHolder.newInstance().dataProcess.mqttServer.send(info.toJSONString());

//        JSONObject dataInfo = new JSONObject();
//        dataInfo.put("func", "02");
//        List<JSONObject> items = new LinkedList<>();
//
//        JSONObject item = new JSONObject();
//        item.put("name", "文件上传");
//        item.put("value", "第 1 包");
//        items.add(item);
//
//        item = new JSONObject();
//        item.put("name", "文件上传");
//        item.put("value", "已上传完成");
//        items.add(item);
//        dataInfo.put("data", items);
//
//        DataProcessHolder.newInstance().dataProcess.SubmitRelayManageTask("418A800001", dataInfo);
        return "ok";
    }

    @GetMapping(value = "DataCollectServer/Manage/Test")
    public Object Test() {
        try {
            //String dataGram = "7E7E000000000091000045800802000021042809300505F3BB";
            String dataGram = "7E7E010212345678000034004E0202BA210720130014F1F1021234567848F0F02107201205F4600000000000000000000000002619000155F6C009C409C409C409C509C509C509C509C509C509C509C509C5452000000480381214080388D3";
            SimpleDateFormat timeFormat2 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            List<String> viewInfoList = new LinkedList<>();
            byte[] data_gram_buff = BytesHelp.hexStr2Bytes(dataGram);
            if (dataGram.substring(0, 2).equals("68")) {
                //String collectTime = dataGram.substring(dataGram.length() - 7 * 2, dataGram.length() - 2 * 2);
                //String collectTime2 = "2020-" + collectTime.substring(8) + "-" + collectTime.substring(6, 8) + " " + collectTime.substring(4, 6) + ":" + collectTime.substring(2, 4) + ":" + collectTime.substring(0, 2);
                //viewInfoList.add("观测时间:" + collectTime2);
                DataTemplateLine line = DataTemplateManager.newInstance().createTemplateLine(GBConstants.AGREEMENT_KIND_SZY);
                line.Stream(data_gram_buff);
                TemplateLineNode macth = line.MacthTemplate();
                if (null != macth) {
                    DataTemplateInterface dataTemplateInterface = macth.getDataTemplate();
                    StringBuffer dataStr = new StringBuffer(BytesHelp.byte2HexStr(dataTemplateInterface.CollectTime()));
                    String tm = dataStr.toString();
                    if (tm != null && tm.length() > 0) {
                        tm = "20" + tm;
                        Date tm1 = timeFormat.parse(tm);
                        viewInfoList.add("观测时间 " + timeFormat2.format(tm1));
                    }
                    LinkedList<DataItemTemplateInterface> dataItem = dataTemplateInterface.MacthDataItem("wq_river");
                    if (dataItem.size() > 0) {
                        // PptnEntity pptnEntity = new PptnEntity();
                        for (DataItemTemplateInterface item : dataItem) {
                            //  item.SetEntity(pptnEntity);
                            viewInfoList.add(item.GetDesc() + " " + item.toString());
                        }
                    }
//                    dataItem = dataTemplateInterface.MacthDataItem("wq_river");
//                    if (dataItem.size() > 0) {
//                        // PptnEntity pptnEntity = new PptnEntity();
//                        for (DataItemTemplateInterface item : dataItem) {
//                            //  item.SetEntity(pptnEntity);
//                            viewInfoList.add(item.GetDesc() + " " + item.toString());
//                        }
//                    }
                    dataItem = dataTemplateInterface.MacthDataItem("t_szy_flow_rate");
                    if (dataItem.size() > 0) {
                        // PptnEntity pptnEntity = new PptnEntity();
                        for (DataItemTemplateInterface item : dataItem) {
                            //  item.SetEntity(pptnEntity);
                            viewInfoList.add(item.GetDesc() + " " + item.toString());
                        }
                    }
                    dataItem = dataTemplateInterface.MacthDataItem("t_szy_warining_info");
                    if (dataItem.size() > 0) {
                        // PptnEntity pptnEntity = new PptnEntity();
                        for (DataItemTemplateInterface item : dataItem) {
                            //  item.SetEntity(pptnEntity);
                            viewInfoList.add(item.GetDesc() + " " + item.toString());
                        }
                    }
                    dataItem = dataTemplateInterface.MacthDataItem("t_szy_status_info");
                    if (dataItem.size() > 0) {
                        // PptnEntity pptnEntity = new PptnEntity();
                        for (DataItemTemplateInterface item : dataItem) {
                            //  item.SetEntity(pptnEntity);
                            viewInfoList.add(item.GetDesc() + " " + item.toString());
                        }
                    }
                    dataItem = dataTemplateInterface.MacthDataItem("t_base_rtu_info");
                    if (dataItem.size() > 0) {
                        for (DataItemTemplateInterface item : dataItem) {
                            viewInfoList.add(item.GetDesc() + " " + item.toString());
                        }
                    }
                }
            } else {
                DataTemplateLine line = DataTemplateManager.newInstance().createTemplateLine(GBConstants.AGREEMENT_KIND_SW);
                line.Stream(data_gram_buff);
                TemplateLineNode macth = line.MacthTemplate();
                if (null != macth) {
                    DataTemplateInterface dataTemplateInterface = macth.getDataTemplate();
                    StringBuffer dataStr = new StringBuffer(BytesHelp.byte2HexStr(dataTemplateInterface.CollectTime()));
                    String tm = dataStr.toString();
                    if (tm != null && tm.length() > 0) {
                        tm = "20" + tm + "00";
                        Date tm1 = timeFormat.parse(tm);
                        viewInfoList.add("观测时间 " + timeFormat2.format(tm1));
                    }
                    dataStr = new StringBuffer(BytesHelp.byte2HexStr(dataTemplateInterface.SendPacketTime()));
                    String dt = dataStr.toString();
                    if (dt != null && dt.length() > 0) {
                        dt = "20" + dt;
                        Date dt1 = timeFormat.parse(dt);
                        viewInfoList.add("发报时间 " + timeFormat2.format(dt1));
                    }
                    LinkedList<DataItemTemplateInterface> dataItem = dataTemplateInterface.MacthDataItem("ST_PPTN_R");
                    if (dataItem.size() > 0) {
                        // PptnEntity pptnEntity = new PptnEntity();
                        for (DataItemTemplateInterface item : dataItem) {
                            //  item.SetEntity(pptnEntity);
                            viewInfoList.add(item.GetDesc() + " " + item.GetDecimal());
                        }
                    }
                    dataItem = dataTemplateInterface.MacthDataItem("st_pptn_r_5_min");
                    if (dataItem.size() > 0) {
                        //  PptnEntity pptnEntity = new PptnEntity();
                        for (DataItemTemplateInterface item : dataItem) {
                            //  item.SetEntity(pptnEntity);
                            viewInfoList.add(item.GetDesc() + " " + item.GetDecimal());
                        }
                        //viewInfoList.add("分钟雨量 " + pptnEntity.getDRP().toString());
                    }
                    dataItem = dataTemplateInterface.MacthDataItem("st_river_r");
                    if (dataItem.size() > 0) {
                        for (DataItemTemplateInterface item : dataItem) {
                            viewInfoList.add(item.GetDesc() + " " + item.GetDecimal());
                        }
                    }
                    dataItem = dataTemplateInterface.MacthDataItem("st_rsvr_r");
                    if (dataItem.size() > 0) {
                        // RsvrEntity rsvrEntity = new RsvrEntity();
                        for (DataItemTemplateInterface item : dataItem) {
                            // item.SetEntity(rsvrEntity);
                            viewInfoList.add(item.GetDesc() + " " + item.GetDecimal());
                        }
                        //viewInfoList.add("水库水位 " + rsvrEntity.getRZ().toString());
                    }

                    dataItem = dataTemplateInterface.MacthDataItem("st_water_level_drz");
                    if (dataItem.size() > 0) {
                        for (DataItemTemplateInterface item : dataItem) {
                            viewInfoList.add(item.GetDesc() + " " + item.toString());
                        }
                    }

                    dataItem = dataTemplateInterface.MacthDataItem("t_base_rtu_info");
                    if (dataItem.size() > 0) {
                        for (DataItemTemplateInterface item : dataItem) {
                            viewInfoList.add(item.GetDesc() + " " + item.toString());
                        }
                    }
                    dataItem = dataTemplateInterface.MacthDataItem("st_ground");
                    if (dataItem.size() > 0) {
                        for (DataItemTemplateInterface item : dataItem) {
                            viewInfoList.add(item.GetDesc() + " " + item.toString());
                        }
                    }
                    dataItem = dataTemplateInterface.MacthDataItem("wr_water_qa");
                    if (dataItem.size() > 0) {
                        for (DataItemTemplateInterface item : dataItem) {
                            viewInfoList.add(item.GetDesc() + " " + item.toString());
                        }
                    }
                    dataItem = dataTemplateInterface.MacthDataItem("st_sw_water");
                    if (dataItem.size() > 0) {
                        for (DataItemTemplateInterface item : dataItem) {
                            viewInfoList.add(item.GetDesc() + " " + item.toString());
                        }
                    }
                    dataItem = dataTemplateInterface.MacthDataItem("st_weather");
                    if (dataItem.size() > 0) {
                        for (DataItemTemplateInterface item : dataItem) {
                            viewInfoList.add(item.GetDesc() + " " + item.toString());
                        }
                    }
                }
            }
            for (String str : viewInfoList) {
                LogHelper.info(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "ok";
    }


    @GetMapping(value = "DataCollectServer/Manage/Test/Send")
    public Object TestSend1() {

        //2021-01-26 15:16:06.660 {"address":"北京市海淀区长春桥路","lng":"116.29845","openid":"oprB55IqrjOkBMqHa8jmbt7hqsCI","weather":"晴 9度 北风 风速21公里/小时 湿度13","rtuCode":"0082828800","photos":[{"id":"757ef583faf04d43bce4beaafce06f8b"}],"orgId":"","lat":"39.95933","desc":"t"}

        JSONArray photos = new JSONArray();
        JSONObject p = new JSONObject();
        p.put("id", "757ef583faf04d43bce4beaafce06f8b");
        photos.add(p);
        JSONObject data = new JSONObject();
        data.put("photos", photos);
        //   wxService.report(data,"oprB55IqrjOkBMqHa8jmbt7hqsCI");

//        String gram ="7E7E0100512075820D0C3200210201D1200227135521F1F1005120758250F0F020022416452219000005261900066503268D";
        //    String gram2 = "7E7E0100512220900D0C320025020202200227135520F1F1005122209050F0F020022616001B19000000261900088038120823033ED7";
//
//        DataProcessHolder.newInstance().dataProcess.SubmitDataGramTask(gram);
        // String gram2 = "7E7E0100828288020000F5006A020108200707132503FF50122499FF51121198FF52122837FF5348444832303031323032FF545089860410011890119257FF550800FF560800FF576000660066FFFFFFFFFFFF0066FF59100000FF6010000BFF61100001FF62100040FF63110300FF64121261FF6512000203F8EE";
//
//        DataProcessHolder.newInstance().dataProcess.SubmitDataGramTask(gram2);
        String gram2 = "686F68BE1508003C00F5271019180820FF50121899FF51121178FF52122668FF5348444832303031303739FF5450898604611619C3352017FF550800FF560802FF576000030003FFFFFFFFFFFF0003FF59100000FF60100000FF61100000FF62100000FF63110000FF64120000FF651200000916";
        // String gram = "7E7E001234567805000034002B0204FB200602110000F1F1123456780548F0F0200602110038121363FF801A003868FF850826FF8118000000035E6A";
        //681468B2150700003BC0305700000000500001051527088516
        String gram = "7E7E0100613060400000320081020058210119170507F1F1006130604048F0F02101191705FF10280001FFFFFFFF10280002FFFFFFFF10280003FFFFFFFF10280004FFFFFFFF10280005FFFFFFFF10280006FFFFFFFF10280007FFFFFFFF10280008FFFFFFFF10280009FFFFFFFF10280010FFFFFFFF10280011FFFFFFFF10280012FFFFFF45200000048038121285030019";

        gram = "7E7E5A0020160011007B330027020078210127145534F1F1002016001148F0F021012714553923000002604520000004803812E754033291";

        gram = "7E7E01008000000100002F000802985C2102172259020342F4";

//        JSONObject body = new JSONObject();
//        body.put(GBConstants.BASE_KEY_DATAGRAM, gram);
//        body.put(GBConstants.BASE_KEY_RTU, "0020160011");
//        body.put(GBConstants.BASE_KEY_AGREEMENT, GBConstants.AGREEMENT_KIND_SW);
//        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
//        body.put(GBConstants.BASE_KEY_DATAGRAM_PICK_TM,timeFormat.format(new Date()));
//        DataProcessHolder.newInstance().dataProcess.SubmitSw2014DataGramTask(body.toJSONString());

        DataProcessHolder.newInstance().dataProcess.SubmitSw2014DataGramRelayTask("0080000001", new Date(), new Date(), "120.224.81.196:6666", gram);


        // DataProcessHolder.newInstance().dataProcess.SubmitSw2014DataGramRelayTask("0012345678", new Date(), new Date(), "172.9.0.195:8008", data);
//        JSONObject body = new JSONObject();

//        body.put("text", "8715268358");
//        body.put("func","45");

//        body.put("stcd", "8715268358");
//        body.put("dataGram", gram2);
//        Map<String, Object> result = null;
//        try {
//            RestTemplate restTemplate = new RestTemplate();
//            //result = restTemplate.postForObject(new URI("http://localhost:8081/rtuManage/query/notify"), body, JSONObject.class);
//            result = restTemplate.postForObject(new URI("http://localhost:8804/DataCollectServer/Manage/GramData/toViewInfo"), body, JSONObject.class);
//
//            if (result != null) {
//                String code = (String) result.get("code");
//                if (code.equals("0")) {
//                    List<String> info = (List<String>) result.get("info");
//                    for (String text : info) {
//                        LogHelper.info(text);
//                    }
//                }
//            }
//        } catch (URISyntaxException e) {
//            e.printStackTrace();
//        }
        JSONObject response = new JSONObject();
        response.put("code", "0");
        return response;
    }

    @GetMapping(value = "DataCollectServer/Manage/Test/Send/{data}")
    @ResponseBody
    public Object TestSend(@PathVariable(name = "data") String data) {

//        String gram ="7E7E0100512075820D0C3200210201D1200227135521F1F1005120758250F0F020022416452219000005261900066503268D";
        //    String gram2 = "7E7E0100512220900D0C320025020202200227135520F1F1005122209050F0F020022616001B19000000261900088038120823033ED7";
//
//        DataProcessHolder.newInstance().dataProcess.SubmitDataGramTask(gram);
        // String gram2 = "7E7E0100828288020000F5006A020108200707132503FF50122499FF51121198FF52122837FF5348444832303031323032FF545089860410011890119257FF550800FF560800FF576000660066FFFFFFFFFFFF0066FF59100000FF6010000BFF61100001FF62100040FF63110300FF64121261FF6512000203F8EE";
//
//        DataProcessHolder.newInstance().dataProcess.SubmitDataGramTask(gram2);
        String gram2 = "686F68BE1508003C00F5271019180820FF50121899FF51121178FF52122668FF5348444832303031303739FF5450898604611619C3352017FF550800FF560802FF576000030003FFFFFFFFFFFF0003FF59100000FF60100000FF61100000FF62100000FF63110000FF64120000FF651200000916";
        // String gram = "7E7E001234567805000034002B0204FB200602110000F1F1123456780548F0F0200602110038121363FF801A003868FF850826FF8118000000035E6A";
        //681468B2150700003BC0305700000000500001051527088516
        String gram = "7E7E0100613060400000320081020058210119170507F1F1006130604048F0F02101191705FF10280001FFFFFFFF10280002FFFFFFFF10280003FFFFFFFF10280004FFFFFFFF10280005FFFFFFFF10280006FFFFFFFF10280007FFFFFFFF10280008FFFFFFFF10280009FFFFFFFF10280010FFFFFFFF10280011FFFFFFFF10280012FFFFFF45200000048038121285030019";

        gram = "7E7E010000000055000032008102111C210120151506F1F100000000555AF0F02101201515FF10280001FFFFFFFF10280002FFFFFFFF10280003FFFFFFFF10280004FFFFFFFF10280005FFFFFFFF10280006FFFFFFFF10280007FFFFFFFF10280008FFFFFFFF10280009FFFFFFFF10280010FFFFFFFF10280011FFFFFFFF10280012FFFFFF4520000004803812129203E835";

        JSONObject body = new JSONObject();
        body.put(GBConstants.BASE_KEY_DATAGRAM, data);
        body.put(GBConstants.BASE_KEY_RTU, "0000000055");
        body.put(GBConstants.BASE_KEY_AGREEMENT, GBConstants.AGREEMENT_KIND_SW);
        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        body.put(GBConstants.BASE_KEY_DATAGRAM_PICK_TM, timeFormat.format(new Date()));
        DataProcessHolder.newInstance().dataProcess.SubmitSw2014DataGramTask(body.toJSONString());


        // DataProcessHolder.newInstance().dataProcess.SubmitSw2014DataGramRelayTask("0012345678", new Date(), new Date(), "172.9.0.195:8008", data);
//        JSONObject body = new JSONObject();

//        body.put("text", "8715268358");
//        body.put("func","45");

//        body.put("stcd", "8715268358");
//        body.put("dataGram", gram2);
//        Map<String, Object> result = null;
//        try {
//            RestTemplate restTemplate = new RestTemplate();
//            //result = restTemplate.postForObject(new URI("http://localhost:8081/rtuManage/query/notify"), body, JSONObject.class);
//            result = restTemplate.postForObject(new URI("http://localhost:8804/DataCollectServer/Manage/GramData/toViewInfo"), body, JSONObject.class);
//
//            if (result != null) {
//                String code = (String) result.get("code");
//                if (code.equals("0")) {
//                    List<String> info = (List<String>) result.get("info");
//                    for (String text : info) {
//                        LogHelper.info(text);
//                    }
//                }
//            }
//        } catch (URISyntaxException e) {
//            e.printStackTrace();
//        }
        JSONObject response = new JSONObject();
        response.put("code", "0");
        return response;
    }


    @GetMapping(value = "DataCollectServer/Manage/FlowSpeed/List/{rtuCode}")
    @ResponseBody
    public JSONObject flowSpeedList(@PathVariable(name = "rtuCode") String rtuCode) {

        WqService wqService = DataProcessHolder.newInstance().dataProcess.wqService;
        List<Map<String, Object>> list = wqService.QuerySpeedListAll(rtuCode, 320);
        JSONObject body = new JSONObject();
        JSONObject data = new JSONObject();
        body.put("code", "0");
        JSONArray dateTime = new JSONArray();
        JSONArray speed = new JSONArray();
        JSONArray correctSpeed = new JSONArray();
        // JSONArray correctSpeed2 = new JSONArray();
        SimpleDateFormat timeFormat = new SimpleDateFormat("dd日HH时mm分");
        for (int i = list.size(); i > 0; i--) {
            Map<String, Object> m = list.get(i - 1);
            Date tm = new Date(((Timestamp) m.get("TM")).getTime());
            dateTime.add(timeFormat.format(tm));
            speed.add(Double.parseDouble((String) m.get("SPEED")));
            Object sc = m.get("SPEED_CORRECT");
            if (null != sc) {
                correctSpeed.add(Double.parseDouble((String) m.get("SPEED_CORRECT")));
            } else {
                correctSpeed.add(0.0);
            }

            //   correctSpeed2.add(Double.parseDouble((String) m.get("SPEED_CORRECT2")));
        }
        data.put("dateTime", dateTime);
        data.put("speed", speed);
        data.put("correctSpeed", correctSpeed);
        //   data.put("correctSpeed2", correctSpeed2);
        body.put("data", data);
        return body;
    }

    private double bottomChanging(int x, int bottom) {
        double log = Math.log10(x) / Math.log10(bottom);
        return log;
    }


    private boolean CheckCorrect(String rtuCode, Date tm, double predictValue) {
        try {
            WqService wqService = DataProcessHolder.newInstance().dataProcess.wqService;
            int ext = 300;
            int trees = 10;
            int samples = 256;
            int treeLevel = 8;
            List<Double> dataValue = new ArrayList<>();
            int limit = trees * samples / ext;
            if (limit * ext < trees * samples) {
                limit += 1;
            }
            limit += 1;

            SimpleDateFormat timeFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = timeFormat2.format(tm);
            List<Map<String, Object>> list = wqService.QuerySpeedListByTm(rtuCode, limit, time);
            if (list.size() * ext < trees * samples) {
                return false;
            }
            List<Double> extList = new ArrayList<>();
            Map<String, Object> prePoint = list.get(list.size() - 1);
            double preValue = Double.parseDouble((String) prePoint.get("SPEED"));
            for (int i = list.size() - 1; i > 0; i--) {
                Map<String, Object> point = list.get(i - 1);
                double value = Double.parseDouble((String) point.get("SPEED"));
                double addValue = (value - preValue) / ext;
                extList.add(preValue);
                for (int j = 1; j < ext; j++) {
                    preValue += addValue;
                    extList.add(preValue);
                }
                preValue = value;
            }

            for (int i = 0; i < trees * samples; i++) {
                dataValue.add(extList.get(extList.size() - 1 - i));
            }

            Collections.shuffle(dataValue);

            List<Double> shuffledatas = new ArrayList<>();
            for (int n = dataValue.size(); n > 0; n--) {
                shuffledatas.add(dataValue.get(n - 1));
            }
            Collections.shuffle(shuffledatas);

            int check = IForestCheckHelp.IForestPredict(shuffledatas, predictValue, trees, samples, treeLevel);
            if (check == IForestCheckHelp.PREDICT_OUTLIERS) {
                return true;
            }
        } catch (Exception e) {
            LogHelper.error(e);
        }
        return false;
    }


    @GetMapping(value = "DataCollectServer/Manage/Speed/Test2")
    public String SpeedTest2() {
        try {
            SimpleDateFormat timeFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            WqService wqService = DataProcessHolder.newInstance().dataProcess.wqService;
            String sql = " SELECT * FROM wq_river r WHERE r.STCD='150400005E' and r.SPEED is not null";
            sql += " and TM >= '2021-03-01 00:00:01' ORDER BY TM  limit 2000";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);

            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> m = list.get(0);
                String rtuCode = (String) m.get("STCD");
                double value = Double.parseDouble((String) m.get("SPEED"));
                Timestamp t = (Timestamp) m.get("TM");
                Date tm = new Date(t.getTime());
                if (this.CheckCorrect(rtuCode, tm, value)) {

                    double correctValue = 0.0;
                    List<Map<String, Object>> correctSpeeds = wqService.QueryCorrectSpeedList(rtuCode, timeFormat2.format(tm), 1);
                    if (null != correctSpeeds && correctSpeeds.size() == 1) {
                        Map<String, Object> c = correctSpeeds.get(0);
                        correctValue = Double.parseDouble((String) c.get("SPEED_CORRECT"));
                    } else {
                        correctValue = value / 2;
                    }

                    Timestamp saveTm = new Timestamp(tm.getTime());
                    String saveValue = new BigDecimal(correctValue).toPlainString();

                    sql = "UPDATE  wq_river set SPEED_CORRECT2=? where tm =?";

                    jdbcTemplate.update(sql, new PreparedStatementSetter() {
                        @Override
                        public void setValues(PreparedStatement preparedStatement) throws SQLException {
                            int count = 0;
                            preparedStatement.setString(++count, saveValue);
                            preparedStatement.setTimestamp(++count, saveTm);
                        }
                    });
                } else {
                    Timestamp saveTm = new Timestamp(tm.getTime());
                    String saveValue = new BigDecimal(value / 2).toPlainString();

                    sql = "UPDATE  wq_river set SPEED_CORRECT2=? where tm =?";

                    jdbcTemplate.update(sql, new PreparedStatementSetter() {
                        @Override
                        public void setValues(PreparedStatement preparedStatement) throws SQLException {
                            int count = 0;
                            preparedStatement.setString(++count, saveValue);
                            preparedStatement.setTimestamp(++count, saveTm);
                        }
                    });
                }
            }

            LogHelper.info("end******************************");
        } catch (Exception e) {

        }
        return "ok";
    }

    @GetMapping(value = "DataCollectServer/Manage/Speed/Test")
    public String SpeedTest() {
        try {

            //   int maxLength = (int) Math.ceil(bottomChanging(256, 2));


            // double dd = (double)0.6/300;

            WqService wqService = DataProcessHolder.newInstance().dataProcess.wqService;
            String sql = " SELECT * FROM wq_river r WHERE r.STCD='150400005E' and r.SPEED is not null";
            sql += " and TM >= '2021-03-01 00:00:01' ORDER BY TM  limit 2000";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);

            List<Map<String, Object>> extList = new ArrayList<>();
            int extNum = (5 * 60);
            for (int i = 1; i < list.size(); i++) {
                Map<String, Object> prepoint = list.get(i - 1);
                double prepointValue = Double.parseDouble((String) prepoint.get("SPEED"));

                prepointValue = prepointValue;

                Map<String, Object> point = list.get(i);
                Timestamp tm = (Timestamp) point.get("TM");

                double pointValue = Double.parseDouble((String) point.get("SPEED"));

                pointValue = pointValue;


                double addValue = (pointValue - prepointValue) / extNum;

                for (int j = 0; j < extNum; j++) {
                    Map<String, Object> p = new HashMap<>();
                    p.put("TM", tm);

                    prepointValue += addValue;
                    //  prepointValue = pointValue;
                    p.put("SPEED", String.format("%.03f", prepointValue));

                    extList.add(p);
                }
            }

            int tree = 10;
            int samples = 256;

            int s = tree * samples / extNum + 1;

            List<Double> datas = new ArrayList<>();
            for (int i = s; i < list.size() - 1; i++) {
                Map<String, Object> point = list.get(i);
                double pointValue = Double.parseDouble((String) point.get("SPEED"));
                Timestamp pointTm = (Timestamp) point.get("TM");
                datas.clear();
                int index = (i + 1) * extNum - tree * samples;
//                for (int j = 0; j<extList.size(); j++) {
//                    Map<String, Object> m = extList.get(j);
//                    Timestamp tm = (Timestamp) m.get("TM");
//                    if (pointTm.getTime()==tm.getTime()){
//                        index=j;
//                        break;
//                    }
//                }

                for (int k = index; k < (i + 1) * extNum; k++) {
                    Map<String, Object> m = extList.get(k);
                    String sp = (String) m.get("SPEED");
                    double v = Double.parseDouble(sp);
                    datas.add(v);

                    //  System.out.println(sp+" **** "+v);
                }


                Collections.shuffle(datas);

                List<Double> shuffledatas = new ArrayList<>();
                for (int n = datas.size(); n > 0; n--) {
                    shuffledatas.add(datas.get(n - 1));
                }
                // Thread.sleep(100);
                Collections.shuffle(shuffledatas);
                //  Collections.shuffle(datas);

                int p = IForestCheckHelp.IForestPredict(shuffledatas, pointValue, tree, samples, 8);

                Map<String, Object> prepoint = list.get(i - 1);
                if (p == IForestCheckHelp.PREDICT_OUTLIERS) {
                    String currValue = (String) point.get("SPEED");

                    String saveValue = (String) prepoint.get("SPEED_CORRECT2");
                    System.out.println(currValue + " out line");
                    Timestamp saveTm = (Timestamp) point.get("TM");
                    sql = "UPDATE  wq_river set SPEED_CORRECT2=? where tm =?";

                    jdbcTemplate.update(sql, new PreparedStatementSetter() {
                        @Override
                        public void setValues(PreparedStatement preparedStatement) throws SQLException {
                            int count = 0;
                            preparedStatement.setString(++count, saveValue);
                            preparedStatement.setTimestamp(++count, saveTm);
                        }
                    });
                } else {
                    String saveValue = (String) point.get("SPEED");

                    System.out.println(saveValue + " nor");

                    Timestamp saveTm = (Timestamp) point.get("TM");
                    sql = "UPDATE  wq_river set SPEED_CORRECT2=? where tm =?";

                    jdbcTemplate.update(sql, new PreparedStatementSetter() {
                        @Override
                        public void setValues(PreparedStatement preparedStatement) throws SQLException {
                            int count = 0;
                            preparedStatement.setString(++count, saveValue);
                            preparedStatement.setTimestamp(++count, saveTm);
                        }
                    });
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return "ok";
    }

    @GetMapping(value = "DataCollectServer/Manage/Test/Update/{rtu}")
    public String TestUpdate(@PathVariable(name = "rtu") String rtu) {


        String path = "E:\\dh_svn\\Project\\DHRJ-DATA-COLLECT\\rtu2.02_20200328.bin";
        //  String path = "/Users/baiying/Documents/dh_svn/DHRJ-DATA-COLLECT/rtu2.02_20191230.bin";
//        File file = new File(path);

        String datagram = "";
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(path));
            int len = bis.available();
            byte[] b = new byte[len];
            bis.read(b, 0, len);
         //   BASE64Encoder encoder = new BASE64Encoder();
            byte[] buff = Base64.getEncoder().encode(b);
            datagram=BytesHelp.byte2HexStr(buff);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        JSONObject body = new JSONObject();
        body.put("datagram", datagram);
        body.put("rtucode", rtu);
        body.put("binFile", "rtu2.02_20200328.bin");
        body.put("configFile", "config.txt");
        body.put("savePath", "0:/updata/");

        //  body.put("funcCode", "F1");


        JSONObject result = null;
        try {
            RestTemplate restTemplate = new RestTemplate();
            result = restTemplate.postForObject(new URI("http://localhost:8803/DataCollectServer/Manage/Rtu/BinFile"), body, JSONObject.class);

            if (result != null) {
                if (result.getString("code").equals("0")) {

                }
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        return "ok";
    }

    @GetMapping(value = "DataCollectServer/Manage/Test/AllCommand")
    public String TestAllCommand() {
        String cmd = "7e7e00828288009145800802000020032514242405269a";

        RestTemplate restTemplate = new RestTemplate();

        JSONObject body = new JSONObject();
        body.put("rtucode", "0082828800");
        body.put("datagram", cmd);
        body.put("funcCode", "45");

        JSONObject result = null;
        try {
            result = restTemplate.postForObject(new URI("http://localhost:8803/DataCollectServer/Manage/Command"), body, JSONObject.class);

            if (result != null) {
                if (result.getString("code").equals("0")) {

                }
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return "ok";
    }

    @GetMapping(value = "DataCollectServer/Manage/Test/Command")
    public String TestCommand() {
        String cmd = "7E7E8715268358010000F480630200012003272022240001000100550A636F6E6669672E7478744C4556454C3A320D0A43524331363A2038322C2032330D0A434E543A300D0A5245533A310D0A5645523A727475322E30325F32303230303332362E62696E0D0A059A47";

        RestTemplate restTemplate = new RestTemplate();

        JSONObject body = new JSONObject();
        body.put("rtucode", "0000003003");
        body.put("datagram", cmd);
        body.put("funcCode", "F5");

        JSONObject result = null;
        try {
            result = restTemplate.postForObject(new URI("http://localhost:8803/DataCollectServer/Manage/Rtu/Command"), body, JSONObject.class);

            if (result != null) {
                if (result.getString("code").equals("0")) {

                }
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return "ok";
    }


    /**
     * 清空指令
     *
     * @param rtuCode
     * @return
     */
    @GetMapping(value = "DataCollectServer/Manage/Setting/Command/{rtuCode}")
    @ResponseBody
    public Object ClearCommand(@PathVariable(name = "rtuCode") String rtuCode) {
        JSONObject respones = new JSONObject();
        try {
            RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
            HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
            if (opsHash.hasKey(rtuCode, GBConstants.REDIS_KEY_COMMAND_FILE)) {
                opsHash.delete(rtuCode, GBConstants.REDIS_KEY_COMMAND_FILE);
            }
            DataProcess.ClearCommand(rtuCode, GBConstants.REDIS_KEY_COMMAND_FILE);
            if (opsHash.hasKey(rtuCode, GBConstants.REDIS_KEY_COMMAND_SETTING)) {
                opsHash.delete(rtuCode, GBConstants.REDIS_KEY_COMMAND_SETTING);
            }
            DataProcess.ClearCommand(rtuCode, GBConstants.REDIS_KEY_COMMAND_SETTING);
            if (opsHash.hasKey(rtuCode, GBConstants.REDIS_KEY_COMMAND_QUERY)) {
                opsHash.delete(rtuCode, GBConstants.REDIS_KEY_COMMAND_QUERY);
            }
            DataProcess.ClearCommand(rtuCode, GBConstants.REDIS_KEY_COMMAND_QUERY);
            respones.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);
        } catch (Exception e) {
            LogHelper.error(e);
            respones.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
        }
        return respones;
    }


    @PostMapping(value = "DataCollectServer/Manage/Rtu/Setting/Collect/{stcd}")
    @ResponseBody
    public Object SetRtuSettingCollect(@RequestBody JSONObject body, @PathVariable(name = "stcd") String
            stcd) {
        JSONObject respones = new JSONObject();
        try {


            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            String dataContent = "0D40";
            for (int i = 0; i < 8; i++) {
                String binStr = "";
                for (int j = 7; j >= 0; j--) {

                    String key = "G_" + String.format("%02d", i) + "_V_" + String.format("%02d", j);
                    String v = body.getString(key);
                    if (null != v) {
                        binStr += v;
                    } else {
                        binStr += "0";
                    }
                    //data.put(key, binStr.substring(j, j + 1));
                    //String binStr = BytesHelp.BytesToBinStr(BytesHelp.subBytes(value, i, 1));
                    // binStr = new StringBuilder(binStr).reverse().toString();
                }
                byte[] buff = BytesHelp.BinStrToBytes(binStr);
                dataContent += BytesHelp.byte2HexStr(buff);
            }
            //content += "0120" + "0280" + "0310" + "0C08" + "0D40" + "0F00" + "1008" + "1208";
            String datagram = "7E7E";
            datagram += stcd;
            datagram += "01";
            datagram += "0000";
            datagram += "40";
            //报文长度
            byte[] bodyBuff = BytesHelp.int2Bytes(dataContent.length() / 2 + 2 + 6, 2);
            datagram += "8" + BytesHelp.byte2HexStr(bodyBuff).substring(1);
            datagram += "02";//起始符
            datagram += "0001";//流水号
            //SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            datagram += timeFormat.format(new Date()).substring(2);//发报时间
            datagram += dataContent;
            //结束符
            datagram += "05";
            byte[] buff = BytesHelp.hexStr2Bytes(datagram);
            byte[] crc16 = BytesHelp.crcFun2014(buff);
            byte[] datagrambuff = BytesHelp.arrayApend(buff, crc16);//CRC16

            Date now = new Date();
            String rtuCode = stcd;
            datagram = BytesHelp.byte2HexStr(datagrambuff);
            String funcCode = "40";
//        CommandEntity entity = new CommandEntity();
//        entity.setDatagram(datagram);
//        entity.setRtuCode(rtuCode);
//        entity.setNeedTry(false);
//        entity.setTryCount(0);
//        entity.setCreateTime(now);
//        entity.setLiveTime(24 * 60);
//        entity.setFuncCode(funcCode);
//        entity.setTry(false);
            LogHelper.info("Manage-" + rtuCode + "-" + datagram);
//        if (DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.containsKey(rtuCode)) {
//            LinkedBlockingQueue<CommandEntity> datagramlist = DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.get(rtuCode);
//            datagramlist.clear();
//            datagramlist.offer(entity);
//        } else {
//            LinkedBlockingQueue<CommandEntity> datagramlist = new LinkedBlockingQueue<>();
//            datagramlist.offer(entity);
//            DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.put(rtuCode, datagramlist);
//        }

            DataProcess.SubmitCommand(rtuCode, datagram, funcCode, true);
//        JSONObject response = null;
//        try {
//            RestTemplate restTemplate = new RestTemplate();
//            JSONObject request = new JSONObject();
//            request.put("rtuCode", rtuCode);
//            response = restTemplate.postForObject(new URI(config.getNotifyurl()), request, JSONObject.class);
//            if (response != null) {
//                if (response.getString("code").equals("0")) {
//                    LogHelper.info("*****************  notify   try  download  datagram");
//                }
//            }
//        } catch (URISyntaxException e) {
//            LogHelper.error(e);
//        }
            DataProcess.DownloadNotify(rtuCode);
            respones.put("code", "0");
        } catch (Exception e) {
            respones.put("code", "1");
            LogHelper.error(e);
        }
        return respones;
    }

    @GetMapping(value = "DataCollectServer/Manage/Rtu/Setting/Collect/{stcd}")
    @ResponseBody
    public Object GetRtuSettingCollect(@PathVariable(name = "stcd") String stcd) {
        JSONObject respones = new JSONObject();
        try {
            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            String content = "0D40";
            //content += "0120" + "0280" + "0310" + "0C08" + "0D40" + "0F00" + "1008" + "1208";
            String datagram = "7E7E";
            datagram += stcd;
            datagram += "01";
            datagram += "0000";
            datagram += "41";
            //报文长度
            byte[] bodyBuff = BytesHelp.int2Bytes(content.length() / 2 + 2 + 6, 2);
            datagram += "8" + BytesHelp.byte2HexStr(bodyBuff).substring(1);
            datagram += "02";//起始符
            datagram += "0001";//流水号
            datagram += timeFormat.format(new Date()).substring(2);//发报时间
            datagram += content;
            //结束符
            datagram += "05";
            byte[] buff = BytesHelp.hexStr2Bytes(datagram);
            byte[] crc16 = BytesHelp.crcFun2014(buff);
            byte[] datagrambuff = BytesHelp.arrayApend(buff, crc16);//CRC16

            Date now = new Date();
            String rtuCode = stcd;
            datagram = BytesHelp.byte2HexStr(datagrambuff);
            String funcCode = "41";
//        CommandEntity entity = new CommandEntity();
//        entity.setDatagram(datagram);
//        entity.setRtuCode(rtuCode);
//        entity.setNeedTry(false);
//        entity.setTryCount(0);
//        entity.setCreateTime(now);
//        entity.setLiveTime(24 * 60);
//        entity.setFuncCode(funcCode);
//        entity.setTry(false);
            LogHelper.info("Manage-" + rtuCode + "-" + datagram);
//        if (DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.containsKey(rtuCode)) {
//            LinkedBlockingQueue<CommandEntity> datagramlist = DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.get(rtuCode);
//            datagramlist.clear();
//            datagramlist.offer(entity);
//        } else {
//            LinkedBlockingQueue<CommandEntity> datagramlist = new LinkedBlockingQueue<>();
//            datagramlist.offer(entity);
//            DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.put(rtuCode, datagramlist);
//        }
            DataProcess.SubmitCommand(rtuCode, datagram, funcCode);

            DataProcess.DownloadNotify(rtuCode);
//        JSONObject response = null;
//        try {
//            RestTemplate restTemplate = new RestTemplate();
//            JSONObject request = new JSONObject();
//            request.put("rtuCode", rtuCode);
//            response = restTemplate.postForObject(new URI(config.getNotifyurl()), request, JSONObject.class);
//            if (response != null) {
//                if (response.getString("code").equals("0")) {
//                    LogHelper.info("*****************  notify   try  download  datagram");
//                }
//            }
//        } catch (URISyntaxException e) {
//            LogHelper.error(e);
//        }

            respones.put("code", "0");
        } catch (Exception e) {
            LogHelper.error(e);
            respones.put("code", "1");
        }
        return respones;
    }

    /**
     * 取RTU状态
     *
     * @param stcd
     * @return
     */
    @GetMapping(value = "DataCollectServer/Manage/Rtu/Status/{stcd}")
    @ResponseBody
    public Object RtuStatus(@PathVariable(name = "stcd") String stcd) {
        try {
            SwService swService = DataProcessHolder.newInstance().dataProcess.swService;
            RtuStatusEntity entity = swService.SwRtuStatus(stcd);
            if (null == entity) {
                entity = new RtuStatusEntity();
            }
            entity.setStcd(stcd);
            JSONObject data = (JSONObject) JSONObject.toJSON(entity);
            if (entity.getSunPowerVoltage() == null) {
                data.put("sunPowerStatus", "2");
            } else {
                if (entity.getSunPowerVoltage().doubleValue() <= 0.0) {
                    data.put("sunPowerStatus", "1");
                } else {
                    data.put("sunPowerStatus", "0");
                }
            }

            if (entity.getBatteryPower() == null) {
                data.put("batteryStatus", "2");
            } else {
                if (entity.getBatteryPower().doubleValue() <= 10.0) {
                    data.put("batteryStatus", "1");
                } else {
                    data.put("batteryStatus", "0");
                }
            }
            if (entity.getWaterSe() == null) {
                data.put("waterSe", "2");
            } else {
                data.put("waterSe", entity.getWaterSe());
            }

            /**RTU故障*/
            data.put("rtuStatus", "0");
            data.put("rtuErrorInfo", "正常");
            /**电源电压*/
            if (entity.getVoltage() == null) {
                data.put("rtuStatus", "2");
                data.put("rtuErrorInfo", "未知");
            } else {
                if (entity.getVoltage().doubleValue() <= 10.0) {
                    data.put("rtuStatus", "1");
                    data.put("rtuErrorInfo", "电源电压错误 " + entity.getVoltage());
                }
            }

            /**RTU异常*/
            if (entity.getError() > 0) {
                data.put("rtuStatus", "1");
                data.put("rtuErrorInfo", "RTU异常");
            }
            /**SD卡错误*/
            if (entity.getStatus() > 0) {
                data.put("rtuStatus", "1");
                data.put("rtuErrorInfo", "SD卡错误");
            }
            /**采集时间错误*/
            RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
            HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
            String collectTimeError = opsHash.get(stcd, "collectTimeError");
            JSONObject errorInfo = JSONObject.parseObject(collectTimeError);
            if (null != errorInfo && errorInfo.getString("code").equals("1")) {
                data.put("rtuStatus", "1");
                data.put("rtuErrorInfo", "采集时间错误");

            }

            String cardInfo = opsHash.get(stcd, "cardInfo");
            if (null != cardInfo) {
                JSONObject card = JSONObject.parseObject(cardInfo);
                String totalAmount = card.getString("totalAmount");
                String useAmount = card.getString("useAmount");
                String remainAmount = card.getString("remainAmount ");
                data.put("totalAmount", totalAmount + " KB");
                data.put("useAmount", useAmount + " KB");
                data.put("remainAmount", remainAmount + " KB");
            }

            return data;

        } catch (Exception e) {
            LogHelper.error(e);
        }
        return null;
    }

    /**
     * 解析报文
     *
     * @param body
     * @return
     */
    @PostMapping(value = "DataCollectServer/Manage/GramData/toViewInfo")
    @ResponseBody
    public Object RtuGramDataToViewInfo(@RequestBody JSONObject body) {
        JSONObject result = new JSONObject();
        try {
            SimpleDateFormat timeFormat2 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            List<String> viewInfoList = new LinkedList<>();
            String dataGram = body.getString("dataGram");
            LogHelper.info("dataGram:" + dataGram);
            byte[] data_gram_buff = BytesHelp.hexStr2Bytes(dataGram);
            if (dataGram.substring(0, 2).equals("68")) {
                //String collectTime = dataGram.substring(dataGram.length() - 7 * 2, dataGram.length() - 2 * 2);
                //String collectTime2 = "2020-" + collectTime.substring(8) + "-" + collectTime.substring(6, 8) + " " + collectTime.substring(4, 6) + ":" + collectTime.substring(2, 4) + ":" + collectTime.substring(0, 2);
                //viewInfoList.add("观测时间:" + collectTime2);
                DataTemplateLine line = DataTemplateManager.newInstance().createTemplateLine(GBConstants.AGREEMENT_KIND_SZY);
                line.Stream(data_gram_buff);
                TemplateLineNode macth = line.MacthTemplate();
                if (null != macth) {
                    DataTemplateInterface dataTemplateInterface = macth.getDataTemplate();
                    StringBuffer dataStr = new StringBuffer(BytesHelp.byte2HexStr(dataTemplateInterface.CollectTime()));
                    String tm = dataStr.toString();
                    if (tm != null && tm.length() > 0) {
                        tm = "20" + tm;
                        Date tm1 = timeFormat.parse(tm);
                        viewInfoList.add("观测时间 " + timeFormat2.format(tm1));
                    }
                    LinkedList<DataItemTemplateInterface> dataItem = dataTemplateInterface.MacthDataItem("wq_river");
                    if (dataItem.size() > 0) {
                        // PptnEntity pptnEntity = new PptnEntity();
                        for (DataItemTemplateInterface item : dataItem) {
                            //  item.SetEntity(pptnEntity);
                            viewInfoList.add(item.GetDesc() + " " + item.toString());
                        }
                    }
//                    dataItem = dataTemplateInterface.MacthDataItem("wq_river");
//                    if (dataItem.size() > 0) {
//                        // PptnEntity pptnEntity = new PptnEntity();
//                        for (DataItemTemplateInterface item : dataItem) {
//                            //  item.SetEntity(pptnEntity);
//                            viewInfoList.add(item.GetDesc() + " " + item.toString());
//                        }
//                    }
                    dataItem = dataTemplateInterface.MacthDataItem("t_szy_flow_rate");
                    if (dataItem.size() > 0) {
                        // PptnEntity pptnEntity = new PptnEntity();
                        for (DataItemTemplateInterface item : dataItem) {
                            //  item.SetEntity(pptnEntity);
                            viewInfoList.add(item.GetDesc() + " " + item.toString());
                        }
                    }
                    dataItem = dataTemplateInterface.MacthDataItem("t_szy_warining_info");
                    if (dataItem.size() > 0) {
                        // PptnEntity pptnEntity = new PptnEntity();
                        for (DataItemTemplateInterface item : dataItem) {
                            //  item.SetEntity(pptnEntity);
                            viewInfoList.add(item.GetDesc() + " " + item.toString());
                        }
                    }
                    dataItem = dataTemplateInterface.MacthDataItem("t_szy_status_info");
                    if (dataItem.size() > 0) {
                        // PptnEntity pptnEntity = new PptnEntity();
                        for (DataItemTemplateInterface item : dataItem) {
                            //  item.SetEntity(pptnEntity);
                            viewInfoList.add(item.GetDesc() + " " + item.toString());
                        }
                    }
                    dataItem = dataTemplateInterface.MacthDataItem("t_base_rtu_info");
                    if (dataItem.size() > 0) {
                        for (DataItemTemplateInterface item : dataItem) {
                            viewInfoList.add(item.GetDesc() + " " + item.toString());
                        }
                    }


                }
            } else {
                DataTemplateLine line = DataTemplateManager.newInstance().createTemplateLine(GBConstants.AGREEMENT_KIND_SW);
                line.Stream(data_gram_buff);
                TemplateLineNode macth = line.MacthTemplate();
                if (null != macth) {
                    DataTemplateInterface dataTemplateInterface = macth.getDataTemplate();
                    StringBuffer dataStr = new StringBuffer(BytesHelp.byte2HexStr(dataTemplateInterface.CollectTime()));
                    String tm = dataStr.toString();
                    if (tm != null && tm.length() > 0) {
                        tm = "20" + tm + "00";
                        Date tm1 = timeFormat.parse(tm);
                        viewInfoList.add("观测时间 " + timeFormat2.format(tm1));
                    }
                    dataStr = new StringBuffer(BytesHelp.byte2HexStr(dataTemplateInterface.SendPacketTime()));
                    String dt = dataStr.toString();
                    if (dt != null && dt.length() > 0) {
                        dt = "20" + dt;
                        Date dt1 = timeFormat.parse(dt);
                        viewInfoList.add("发报时间 " + timeFormat2.format(dt1));
                    }
                    LinkedList<DataItemTemplateInterface> dataItem = dataTemplateInterface.MacthDataItem("ST_PPTN_R");
                    if (dataItem.size() > 0) {
                        // PptnEntity pptnEntity = new PptnEntity();
                        for (DataItemTemplateInterface item : dataItem) {
                            //  item.SetEntity(pptnEntity);
                            viewInfoList.add(item.GetDesc() + " " + item.GetDecimal());
                        }
                    }
                    dataItem = dataTemplateInterface.MacthDataItem("st_pptn_r_5_min");
                    if (dataItem.size() > 0) {
                        //  PptnEntity pptnEntity = new PptnEntity();
                        for (DataItemTemplateInterface item : dataItem) {
                            //  item.SetEntity(pptnEntity);
                            viewInfoList.add(item.GetDesc() + " " + item.GetDecimal());
                        }
                        //viewInfoList.add("分钟雨量 " + pptnEntity.getDRP().toString());
                    }
                    dataItem = dataTemplateInterface.MacthDataItem("st_river_r");
                    if (dataItem.size() > 0) {
                        for (DataItemTemplateInterface item : dataItem) {
                            viewInfoList.add(item.GetDesc() + " " + item.GetDecimal());
                        }
                    }
                    dataItem = dataTemplateInterface.MacthDataItem("st_rsvr_r");
                    if (dataItem.size() > 0) {
                        // RsvrEntity rsvrEntity = new RsvrEntity();
                        for (DataItemTemplateInterface item : dataItem) {
                            // item.SetEntity(rsvrEntity);
                            viewInfoList.add(item.GetDesc() + " " + item.GetDecimal());
                        }
                        //viewInfoList.add("水库水位 " + rsvrEntity.getRZ().toString());
                    }

                    dataItem = dataTemplateInterface.MacthDataItem("st_water_level_drz");
                    if (dataItem.size() > 0) {
                        for (DataItemTemplateInterface item : dataItem) {
                            viewInfoList.add(item.GetDesc() + " " + item.toString());
                        }
                    }

                    dataItem = dataTemplateInterface.MacthDataItem("t_base_rtu_info");
                    if (dataItem.size() > 0) {
                        for (DataItemTemplateInterface item : dataItem) {
                            viewInfoList.add(item.GetDesc() + " " + item.toString());
                        }
                    }
                    dataItem = dataTemplateInterface.MacthDataItem("st_ground");
                    if (dataItem.size() > 0) {
                        for (DataItemTemplateInterface item : dataItem) {
                            viewInfoList.add(item.GetDesc() + " " + item.toString());
                        }
                    }
                    dataItem = dataTemplateInterface.MacthDataItem("wr_water_qa");
                    if (dataItem.size() > 0) {
                        for (DataItemTemplateInterface item : dataItem) {
                            viewInfoList.add(item.GetDesc() + " " + item.toString());
                        }
                    }
                    dataItem = dataTemplateInterface.MacthDataItem("st_sw_water");
                    if (dataItem.size() > 0) {
                        for (DataItemTemplateInterface item : dataItem) {
                            viewInfoList.add(item.GetDesc() + " " + item.toString());
                        }
                    }
                    dataItem = dataTemplateInterface.MacthDataItem("st_weather");
                    if (dataItem.size() > 0) {
                        for (DataItemTemplateInterface item : dataItem) {
                            viewInfoList.add(item.GetDesc() + " " + item.toString());
                        }
                    }
                    dataItem = dataTemplateInterface.MacthDataItem("st_watergate");
                    if (dataItem.size() > 0) {
                        for (DataItemTemplateInterface item : dataItem) {
                            viewInfoList.add(item.GetDesc() + " " + item.toString());
                        }
                    }
                    dataItem = dataTemplateInterface.MacthDataItem(GBConstants.TABLE_DRXNN);
                    if (dataItem.size() > 0) {
                        for (DataItemTemplateInterface item : dataItem) {
                            viewInfoList.add(item.GetDesc() + " " + item.toString());
                        }
                    }
                }
            }
            result.put("info", JSONArray.toJSON(viewInfoList));
            result.put("code", "0");
        } catch (Exception e) {
            LogHelper.error(e);
            result.put("code", "1");
        }
        return result;
    }

    /**
     * 水资源,查询测站编码
     *
     * @param rtuCode
     * @return
     */
    @GetMapping(value = "DataCollectServer/Manage/Setting/RtuCode/{rtuCode}")
    @ResponseBody
    public Object getRtuCodeInfo(@PathVariable(name = "rtuCode") String rtuCode) {
        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String content = "30" + rtuCode + "50";
        byte[] buff = BytesHelp.hexStr2Bytes(content);
        byte[] crc = new byte[1];
        crc[0] = BytesHelp.GetCRCByte(buff);
        byte[] lenBuff = new byte[1];
        lenBuff[0] = (byte) (content.length() / 2);
        String datagram = "68" + BytesHelp.byte2HexStr(lenBuff) + "68" + content + BytesHelp.byte2HexStr(crc) + "16";
        byte[] datagrambuff = BytesHelp.hexStr2Bytes(datagram);
        Date now = new Date();
        String funcCode = "50";
        LogHelper.info("Manage-" + rtuCode + "-" + datagram);
        DataProcess.SubmitCommand(rtuCode, datagram, funcCode);
        DataProcess.DownloadNotify(rtuCode);
        JSONObject responesBody = new JSONObject();
        responesBody.put("msg", "指令已发送");
        responesBody.put("code", "0");
        return responesBody;
    }

    /**
     * 查询基本配置信息，包括测站编码，IP地址等
     *
     * @param rtuCode
     * @return
     */
    @GetMapping(value = "DataCollectServer/Manage/Rtu/Setting/Base/{rtuCode}")
    @ResponseBody
    public Object GetRtuSettingBase(@PathVariable(name = "rtuCode") String rtuCode) {
        try {
            RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
            HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
            if (opsHash.hasKey(rtuCode, GBConstants.BASE_KEY_AGREEMENT)) {
                String agreement = opsHash.get(rtuCode, GBConstants.BASE_KEY_AGREEMENT);
                if (agreement.equals(GBConstants.AGREEMENT_KIND_SW)) {

                    SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                    String content = "0250" + "0450" + "0650" + "0850" + "0A50" + "3008" + "3108" + "3208" + "3308";
                    //content +="0D40" + "0120" + "0280" + "0310" + "0C08" + "0D40" + "0F00" + "1008" + "1208";
                    String datagram = "7E7E";
                    datagram += rtuCode;
                    datagram += "01";
                    datagram += "0000";
                    datagram += "41";
                    //报文长度
                    byte[] bodyBuff = BytesHelp.int2Bytes(content.length() / 2 + 2 + 6, 2);
                    datagram += "8" + BytesHelp.byte2HexStr(bodyBuff).substring(1);
                    datagram += "02";//起始符
                    datagram += "0001";//流水号
                    datagram += timeFormat.format(new Date()).substring(2);//发报时间
                    datagram += content;
                    //结束符
                    datagram += "05";
                    byte[] buff = BytesHelp.hexStr2Bytes(datagram);
                    byte[] crc16 = BytesHelp.crcFun2014(buff);
                    byte[] datagrambuff = BytesHelp.arrayApend(buff, crc16);//CRC16

                    Date now = new Date();

                    datagram = BytesHelp.byte2HexStr(datagrambuff);
                    String funcCode = "41";
//                    CommandEntity entity = new CommandEntity();
//                    entity.setDatagram(datagram);
//                    entity.setRtuCode(rtuCode);
//                    entity.setNeedTry(false);
//                    entity.setTryCount(0);
//                    entity.setCreateTime(now);
//                    entity.setLiveTime(24 * 60);
//                    entity.setFuncCode(funcCode);
//                    entity.setTry(false);
                    LogHelper.info("Manage-" + rtuCode + "-" + datagram);
//                    if (DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.containsKey(rtuCode)) {
//                        LinkedBlockingQueue<CommandEntity> datagramlist = DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.get(rtuCode);
//                       datagramlist.clear();
//                        datagramlist.offer(entity);
//                    } else {
//                        LinkedBlockingQueue<CommandEntity> datagramlist = new LinkedBlockingQueue<>();
//                        datagramlist.offer(entity);
//                        DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.put(rtuCode, datagramlist);
//                    }

                    DataProcess.SubmitCommand(rtuCode, datagram, funcCode);

                    DataProcess.DownloadNotify(rtuCode);

//                    RestTemplate restTemplate = new RestTemplate();
//                    JSONObject request = new JSONObject();
//                    request.put("rtuCode", rtuCode);
//                    JSONObject response = restTemplate.postForObject(new URI(config.getNotifyurl()), request, JSONObject.class);
//                    if (response != null) {
//                        if (response.getString("code").equals("0")) {
//                            LogHelper.info("*****************  notify   try  download  datagram");
                    JSONObject responesBody = new JSONObject();
                    responesBody.put("msg", "指令已发送");
                    responesBody.put("code", "0");
                    return responesBody;
//                        }
//                    }


                } else if (agreement.equals("szy2012")) {
                    String version = null;
                    if (opsHash.hasKey(rtuCode, GBConstants.BASE_KEY_ORGID)) {
                        String orgId = opsHash.get(rtuCode, GBConstants.BASE_KEY_ORGID);
                        if (null != orgId) {
                            if (opsHash.hasKey(orgId, GBConstants.BASE_KEY_VERSION)) {
                                version = opsHash.get(orgId, GBConstants.BASE_KEY_VERSION);
                            }
                        }
                    }
                    if (opsHash.hasKey(rtuCode, GBConstants.BASE_KEY_VERSION)) {
                        version = opsHash.get(rtuCode, GBConstants.BASE_KEY_VERSION);
                    }
                    if (null != version && version.length() > 0 && version.equals(GBConstants.VERSION_KEY_SZY_54)) {
                        // if (null != version && version.equals(GBConstants.VERSION_KEY_SZY_54)) {
                        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                        String content = "30" + rtuCode + "87";
                        byte[] buff = BytesHelp.hexStr2Bytes(content);
                        byte[] crc = new byte[1];
                        crc[0] = BytesHelp.GetCRCByte(buff);
                        byte[] lenBuff = new byte[1];
                        lenBuff[0] = (byte) (content.length() / 2);
                        String datagram = "68" + BytesHelp.byte2HexStr(lenBuff) + "68" + content + BytesHelp.byte2HexStr(crc) + "16";

                        byte[] datagrambuff = BytesHelp.hexStr2Bytes(datagram);

                        Date now = new Date();
                        String funcCode = "87";
//                            CommandEntity entity = new CommandEntity();
//                            entity.setDatagram(datagram);
//                            entity.setRtuCode(rtuCode);
//                            entity.setNeedTry(false);
//                            entity.setTryCount(0);
//                            entity.setCreateTime(now);
//                            entity.setLiveTime(24 * 60);
//                            entity.setFuncCode(funcCode);
//                            entity.setTry(false);
                        LogHelper.info("Manage-" + rtuCode + "-" + datagram);
//                            if (DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.containsKey(rtuCode)) {
//                                LinkedBlockingQueue<CommandEntity> datagramlist = DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.get(rtuCode);
//                               datagramlist.clear();
//                                datagramlist.offer(entity);
//                            } else {
//                                LinkedBlockingQueue<CommandEntity> datagramlist = new LinkedBlockingQueue<>();
//                                datagramlist.offer(entity);
//                                DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.put(rtuCode, datagramlist);
//                            }

                        DataProcess.SubmitCommand(rtuCode, datagram, funcCode);

                        DataProcess.DownloadNotify(rtuCode);

//                            RestTemplate restTemplate = new RestTemplate();
//                            JSONObject request = new JSONObject();
//                            request.put("rtuCode", rtuCode);
//                            JSONObject response = restTemplate.postForObject(new URI(config.getNotifyurl()), request, JSONObject.class);
//                            if (response != null) {
//                                if (response.getString("code").equals("0")) {
//                                    LogHelper.info("*****************  notify   try  download  datagram");
                        JSONObject responesBody = new JSONObject();
                        responesBody.put("msg", "指令已发送");
                        responesBody.put("code", "0");
                        return responesBody;
//                                }
//                            }

                    } else {


                        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");


                        String content = "30" + rtuCode + "E8";

                        byte[] buff = BytesHelp.hexStr2Bytes(content);
                        byte[] crc = new byte[1];
                        crc[0] = BytesHelp.GetCRCByte(buff);
                        byte[] lenBuff = new byte[1];
                        lenBuff[0] = (byte) (content.length() / 2);
                        String datagram = "68" + BytesHelp.byte2HexStr(lenBuff) + "68" + content + BytesHelp.byte2HexStr(crc) + "16";

                        byte[] datagrambuff = BytesHelp.hexStr2Bytes(datagram);

                        Date now = new Date();
                        String funcCode = "E8";
//                        CommandEntity entity = new CommandEntity();
//                        entity.setDatagram(datagram);
//                        entity.setRtuCode(rtuCode);
//                        entity.setNeedTry(false);
//                        entity.setTryCount(0);
//                        entity.setCreateTime(now);
//                        entity.setLiveTime(24 * 60);
//                        entity.setFuncCode(funcCode);
//                        entity.setTry(false);
                        LogHelper.info("Manage-" + rtuCode + "-" + datagram);
//                        if (DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.containsKey(rtuCode)) {
//                            LinkedBlockingQueue<CommandEntity> datagramlist = DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.get(rtuCode);
//                            datagramlist.clear();
//                            datagramlist.offer(entity);
//                        } else {
//                            LinkedBlockingQueue<CommandEntity> datagramlist = new LinkedBlockingQueue<>();
//                            datagramlist.offer(entity);
//                            DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.put(rtuCode, datagramlist);
//                        }

                        DataProcess.SubmitCommand(rtuCode, datagram, funcCode);

                        DataProcess.DownloadNotify(rtuCode);

//                        RestTemplate restTemplate = new RestTemplate();
//                        JSONObject request = new JSONObject();
//                        request.put("rtuCode", rtuCode);
//                        JSONObject response = restTemplate.postForObject(new URI(config.getNotifyurl()), request, JSONObject.class);
//                        if (response != null) {
//                            if (response.getString("code").equals("0")) {
//                                LogHelper.info("*****************  notify   try  download  datagram");
                        JSONObject responesBody = new JSONObject();
                        responesBody.put("msg", "指令已发送");
                        responesBody.put("code", "0");
                        return responesBody;
//                            }
//                        }
                    }
                } else {
                    LogHelper.info("dont know agreement");
                    JSONObject responesBody = new JSONObject();
                    responesBody.put("msg", "测站没设置规约");
                    responesBody.put("code", "1");
                    return responesBody;
                }
            } else {
                LogHelper.info("dont know agreement");
                JSONObject responesBody = new JSONObject();
                responesBody.put("msg", "测站没设置规约");
                responesBody.put("code", "1");
                return responesBody;
            }
        } catch (Exception e) {
            LogHelper.error(e);
        }
        return null;
    }


    //@PostMapping(value = "DataCollectServer/Manage/Rtu/Reboot")
    private JSONObject RtuReboot(String rtuCode) {
        JSONObject result = new JSONObject();
        try {
            result.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
            RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
            HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
            //String rtuCode = jsonData.getString(GBConstants.BASE_KEY_RTU);
            if (opsHash.hasKey(rtuCode, GBConstants.BASE_KEY_AGREEMENT)) {
                String agreement = opsHash.get(rtuCode, GBConstants.BASE_KEY_AGREEMENT);
                if (agreement.equals(GBConstants.AGREEMENT_KIND_SW)) {
                    SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                    String tsStr = timeFormat.format(new Date());
                    String message = "7E7E" + rtuCode;
                    message = message + "91" + "0000" + "F3" + "8008" + "02" + "0000" + tsStr.substring(2) + "05";
                    byte[] buff = BytesHelp.hexStr2Bytes(message);
                    byte[] crc16 = BytesHelp.crcFun2014(buff);
                    byte[] datagrambuff = BytesHelp.arrayApend(buff, crc16);//CRC16
                    String datagram = BytesHelp.byte2HexStr(datagrambuff);
                    String funcCode = "F3";
                    LogHelper.info("Manage-" + rtuCode + "-" + datagram);
                    DataProcess.SubmitCommand(rtuCode, datagram, funcCode, true);
                    DataProcess.DownloadNotify(rtuCode);
                } else if (agreement.equals(GBConstants.AGREEMENT_KIND_SZY)) {
                    String version = null;
                    if (opsHash.hasKey(rtuCode, GBConstants.BASE_KEY_ORGID)) {
                        String orgId = opsHash.get(rtuCode, GBConstants.BASE_KEY_ORGID);
                        if (null != orgId) {
                            if (opsHash.hasKey(orgId, GBConstants.BASE_KEY_VERSION)) {
                                version = opsHash.get(orgId, GBConstants.BASE_KEY_VERSION);
                            }
                        }
                    }
                    if (opsHash.hasKey(rtuCode, GBConstants.BASE_KEY_VERSION)) {
                        version = opsHash.get(rtuCode, GBConstants.BASE_KEY_VERSION);
                    }
                    if (null != version && version.length() > 0 && version.equals(GBConstants.VERSION_KEY_SZY_54)) {
                        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                        byte[] dataContent = BytesHelp.hexStr2Bytes("30");//C
                        dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.hexStr2Bytes(rtuCode));//CODE
                        dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.hexStr2Bytes("90"));//ANF
                        byte[] dc = new byte[1];
                        dc[0] = 0x01;
                        dataContent = BytesHelp.arrayApend(dataContent, dc);
                        //pw
                        dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.hexStr2Bytes("0000"));
                        //tp
                        String tp = timeFormat.format(new Date());
                        dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.hexStr2Bytes(tp.substring(tp.length() - 2, tp.length())));
                        dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.hexStr2Bytes(tp.substring(tp.length() - 4, tp.length() - 2)));
                        dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.hexStr2Bytes(tp.substring(tp.length() - 6, tp.length() - 4)));
                        dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.hexStr2Bytes(tp.substring(tp.length() - 8, tp.length() - 6)));
                        dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.hexStr2Bytes("00"));

                        byte[] lenBuff = new byte[1];
                        byte[] crc = new byte[1];
                        crc[0] = BytesHelp.GetCRCByte(dataContent);
                        lenBuff[0] = (byte) dataContent.length;
                        String datagram = "68" + BytesHelp.byte2HexStr(lenBuff) + "68" + BytesHelp.byte2HexStr(dataContent) + BytesHelp.byte2HexStr(crc) + "16";
                        //byte[] datagrambuff = BytesHelp.hexStr2Bytes(datagram);
                        String funcCode = "90";
                        LogHelper.info("Manage-" + rtuCode + "-" + datagram);
                        DataProcess.SubmitCommand(rtuCode, datagram, funcCode, true);
                        DataProcess.DownloadNotify(rtuCode);
                    } else {
                        byte[] respPacket_h = BytesHelp.hexStr2Bytes("680768");  //帧起始符
                        byte[] respPacket = BytesHelp.hexStr2Bytes("30");//中心站地址
                        respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes(rtuCode));//遥测站地址
                        respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("F3"));//功能码
                        byte[] crc = new byte[1]; //系统计算的校验码
                        crc[0] = BytesHelp.GetCRCByte(respPacket);
                        respPacket = BytesHelp.arrayApend(respPacket_h, respPacket);
                        respPacket = BytesHelp.arrayApend(respPacket, crc);//CRC
                        respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("16"));
                        String datagram = BytesHelp.byte2HexStr(respPacket);
                        String funcCode = "F3";
                        LogHelper.info("Manage-" + rtuCode + "-" + datagram);
                        DataProcess.SubmitCommand(rtuCode, datagram, funcCode, true);
                        DataProcess.DownloadNotify(rtuCode);
                    }
                } else {
                    LogHelper.info("dont know agreement");
                    JSONObject responesBody = new JSONObject();
                    responesBody.put("msg", "测站没设置规约");
                    responesBody.put("code", "1");
                    return responesBody;
                }
            } else {
                LogHelper.info("dont know agreement");
                JSONObject responesBody = new JSONObject();
                responesBody.put("msg", "测站没设置规约");
                responesBody.put("code", "1");
                return responesBody;
            }
        } catch (Exception e) {
            LogHelper.error(e);
            result.put("code", "1");
        }
        return result;
    }


    @PostMapping(value = "DataCollectServer/Manage/Rtu/Controller")
    public JSONObject RtuController(@RequestBody JSONObject jsonData) {
        JSONObject result = new JSONObject();
        try {
            String rtuCode = jsonData.getString(GBConstants.BASE_KEY_RTU);
            String dataContent = "01";
            int pumpSize = jsonData.getInteger("pumpSize");
            JSONObject pump = jsonData.getJSONObject("pump");
            String command = "";
            for (int i = 0; i < pumpSize; i++) {
                String key = "pump_" + (i + 1);
                JSONObject p = pump.getJSONObject(key);
                String cmd = p.getString("switch");
                command = cmd + command;
            }
            byte[] commandByte = BytesHelp.BinStrToBytes(command);
            dataContent += BytesHelp.byte2HexStr(commandByte);

            String datagram = "7E7E";
            datagram += jsonData.getString("rtuCode");
            datagram += "01";
            datagram += "0000";
            datagram += "4C";
            //报文长度
            byte[] bodyBuff = BytesHelp.int2Bytes(dataContent.length() / 2 + 2 + 6, 2);
            datagram += "8" + BytesHelp.byte2HexStr(bodyBuff).substring(1);
            datagram += "02";//起始符
            datagram += "0001";//流水号
            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            datagram += timeFormat.format(new Date()).substring(2);//发报时间

            datagram += dataContent;
            //结束符
            datagram += "05";
            byte[] buff = BytesHelp.hexStr2Bytes(datagram);
            byte[] crc16 = BytesHelp.crcFun2014(buff);
            byte[] datagrambuff = BytesHelp.arrayApend(buff, crc16);//CRC16

            datagram = BytesHelp.byte2HexStr(datagrambuff);
            String funcCode = "4C";
            DataProcess.SubmitCommand(rtuCode, datagram, funcCode, true);
            DataProcess.DownloadNotify(rtuCode);
            result.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);
        } catch (Exception e) {
            LogHelper.error(e);
            result.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
        }
        return result;
    }


    /**
     * 设置RTU基本参数,包括测站编码，IP地址等
     *
     * @param jsonData
     */
    @PostMapping(value = "DataCollectServer/Manage/Rtu/BaseSetting")
    public JSONObject RtuBaseSetting(@RequestBody JSONObject jsonData) {
        JSONObject result = new JSONObject();
        try {
            result.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
            RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
            HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
            String rtuCode = jsonData.getString(GBConstants.BASE_KEY_RTU);
            if (opsHash.hasKey(rtuCode, GBConstants.BASE_KEY_AGREEMENT)) {
                String agreement = opsHash.get(rtuCode, GBConstants.BASE_KEY_AGREEMENT);
                if (agreement.equals(GBConstants.AGREEMENT_KIND_SW)) {
                    String dataContent = "";
                    //测站编码
                    if (jsonData.containsKey("newRtuCode")) {
                        String v = jsonData.getString("newRtuCode");
                        byte[] buff = BytesHelp.createBcdBytes((byte) 0x02, v);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }
                    //IP地址1
                    if (jsonData.containsKey("ip1")) {
                        String v = jsonData.getString("ip1");
                        byte[] buff = BytesHelp.createIpBytes((byte) 0x04, v);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }
                    //IP地址2
                    if (jsonData.containsKey("ip2")) {
                        String v = jsonData.getString("ip2");
                        byte[] buff = BytesHelp.createIpBytes((byte) 0x06, v);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }
                    //IP地址3
                    if (jsonData.containsKey("ip3")) {
                        String v = jsonData.getString("ip3");
                        byte[] buff = BytesHelp.createIpBytes((byte) 0x08, v);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }
                    //IP地址4
                    if (jsonData.containsKey("ip4")) {
                        String v = jsonData.getString("ip4");
                        byte[] buff = BytesHelp.createIpBytes((byte) 0x0A, v);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }
                    //工作模式
                    if (jsonData.containsKey("workModel")) {
                        dataContent += "3008";
                        String v = jsonData.getString("workModel");

                        if (v.equals("0")) {
                            dataContent += "00";
                        } else if (v.equals("1")) {
                            dataContent += "01";
                        }
                    }
                    //测站类型
                    if (jsonData.containsKey("rtuKind")) {
                        dataContent += "3108";
                        String v = jsonData.getString("rtuKind");
                        if (v.equals("P") || v.equals("p")) {
                            dataContent += "50";
                        } else if (v.equals("H") || v.equals("h")) {
                            dataContent += "48";
                        } else if (v.equals("K") || v.equals("k")) {
                            dataContent += "4B";
                        } else if (v.equals("Z") || v.equals("z")) {
                            dataContent += "5A";
                        } else if (v.equals("D") || v.equals("d")) {
                            dataContent += "44";
                        } else if (v.equals("T") || v.equals("t")) {
                            dataContent += "54";
                        } else if (v.equals("M") || v.equals("m")) {
                            dataContent += "4D";
                        } else if (v.equals("G") || v.equals("g")) {
                            dataContent += "47";
                        } else if (v.equals("Q") || v.equals("q")) {
                            dataContent += "51";
                        } else if (v.equals("I") || v.equals("i")) {
                            dataContent += "49";
                        } else if (v.equals("O") || v.equals("o")) {
                            dataContent += "4F";
                        }
                    }

                    if (jsonData.containsKey("rainPercenValue")) {
                        String v = jsonData.getString("rainPercenValue");
                        if (v.equals("0") || v.equals("1") || v.equals("2") || v.equals("3") || v.equals("4")) {
                            dataContent += "3208";
                            dataContent += "0" + v;
                        }
                    }

                    if (jsonData.containsKey("bluetoothValue")) {
                        String v = jsonData.getString("bluetoothValue");
                        if (v.equals("0") || v.equals("1")) {
                            dataContent += "3308";
                            dataContent += "0" + v;
                        }
                    }

                    String datagram = "7E7E";
                    datagram += jsonData.getString("rtuCode");
                    datagram += "01";
                    datagram += "0000";
                    datagram += "40";
                    //报文长度
                    byte[] bodyBuff = BytesHelp.int2Bytes(dataContent.length() / 2 + 2 + 6, 2);
                    datagram += "8" + BytesHelp.byte2HexStr(bodyBuff).substring(1);
                    datagram += "02";//起始符
                    datagram += "0001";//流水号
                    SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                    datagram += timeFormat.format(new Date()).substring(2);//发报时间
                    datagram += dataContent;
                    //结束符
                    datagram += "05";
                    byte[] buff = BytesHelp.hexStr2Bytes(datagram);
                    byte[] crc16 = BytesHelp.crcFun2014(buff);
                    byte[] datagrambuff = BytesHelp.arrayApend(buff, crc16);//CRC16

                    // Date now = new Date();

                    datagram = BytesHelp.byte2HexStr(datagrambuff);
                    String funcCode = "40";
//                    CommandEntity entity = new CommandEntity();
//                    entity.setDatagram(datagram);
//                    entity.setRtuCode(rtuCode);
//                    entity.setNeedTry(false);
//                    entity.setTryCount(0);
//                    entity.setCreateTime(now);
//                    entity.setLiveTime(24 * 60);
//                    entity.setFuncCode(funcCode);
//                    entity.setTry(false);
                    LogHelper.info("Manage-" + rtuCode + "-" + datagram);
//                    if (DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.containsKey(rtuCode)) {
//                        LinkedBlockingQueue<CommandEntity> datagramlist = DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.get(rtuCode);
//                        datagramlist.clear();
//                        datagramlist.offer(entity);
//                    } else {
//                        LinkedBlockingQueue<CommandEntity> datagramlist = new LinkedBlockingQueue<>();
//                        datagramlist.offer(entity);
//                        DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.put(rtuCode, datagramlist);
//                    }
                    DataProcess.SubmitCommand(rtuCode, datagram, funcCode, true);
                    DataProcess.DownloadNotify(rtuCode);
//                    JSONObject response = null;
//                    try {
//                        RestTemplate restTemplate = new RestTemplate();
//                        JSONObject request = new JSONObject();
//                        request.put(GBConstants.BASE_KEY_RTU, rtuCode);
//                        response = restTemplate.postForObject(new URI(config.getNotifyurl()), request, JSONObject.class);
//                        if (response != null) {
//                            if (response.getString(GBConstants.HTTP_REQUEST_KEY_CODE).equals(GBConstants.HTTP_REQUEST_KEY_OK)) {
//                                LogHelper.info("*****************  notify   try  download  datagram");
//                                result.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);
//                            }
//                        }
//                    } catch (URISyntaxException e) {
//                        LogHelper.error(e);
//                    }
                } else if (agreement.equals(GBConstants.AGREEMENT_KIND_SZY)) {
                    String version = null;
                    if (opsHash.hasKey(rtuCode, GBConstants.BASE_KEY_ORGID)) {
                        String orgId = opsHash.get(rtuCode, GBConstants.BASE_KEY_ORGID);
                        if (null != orgId) {
                            if (opsHash.hasKey(orgId, GBConstants.BASE_KEY_VERSION)) {
                                version = opsHash.get(orgId, GBConstants.BASE_KEY_VERSION);
                            }
                        }
                    }
                    if (opsHash.hasKey(rtuCode, GBConstants.BASE_KEY_VERSION)) {
                        version = opsHash.get(rtuCode, GBConstants.BASE_KEY_VERSION);
                    }
                    if (null != version && version.length() > 0 && version.equals(GBConstants.VERSION_KEY_SZY_54)) {
                        //    if (null != version && version.equals(GBConstants.VERSION_KEY_SZY_54)) {
                        String setting = opsHash.get(rtuCode, GBConstants.BASE_KEY_SETTING);
                        if (null != setting) {
                            byte[] settingBuff = BytesHelp.hexStr2Bytes(setting);
                            int count = 0;
                            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                            byte[] dataContent = BytesHelp.hexStr2Bytes("30");
                            dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.hexStr2Bytes(rtuCode));

                            dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.hexStr2Bytes("88"));

                            dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.subBytes(settingBuff, 0, 5));
                            count += 5;


                            int ipNum = 0;
                            if (jsonData.containsKey("ip1") && jsonData.containsKey("ip2") && jsonData.containsKey("ip3") && jsonData.containsKey("ip4")) {
                                ipNum = 4;
                            } else if (jsonData.containsKey("ip1") && jsonData.containsKey("ip2") && jsonData.containsKey("ip3")) {
                                ipNum = 3;
                            } else if (jsonData.containsKey("ip1") && jsonData.containsKey("ip2")) {
                                ipNum = 2;
                            } else if (jsonData.containsKey("ip1")) {
                                ipNum = 1;
                            }

                            if (ipNum > 0) {


                                byte[] ipNumBuff = new byte[1];
                                ipNumBuff[0] = (byte) ipNum;

                                dataContent = BytesHelp.arrayApend(dataContent, ipNumBuff);

                                count += 1;

                                dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.subBytes(settingBuff, count, 60));

                                count += 60;

                                byte[] ipbuff = new byte[0];
                                byte[] portbuff = new byte[0];

                                //IP地址1
                                if (jsonData.containsKey("ip1")) {
                                    String ip = jsonData.getString("ip1");
                                    String[] ips = ip.split(":");
                                    String[] texts = ips[0].split("[.]");
                                    String newIp = String.format("%03d", Integer.parseInt(texts[0]));
                                    newIp += "." + String.format("%03d", Integer.parseInt(texts[1]));
                                    newIp += "." + String.format("%03d", Integer.parseInt(texts[2]));
                                    newIp += "." + String.format("%03d", Integer.parseInt(texts[3]));

                                    ipbuff = BytesHelp.arrayApend(ipbuff, newIp.getBytes());

                                    portbuff = BytesHelp.arrayApend(portbuff, BytesHelp.int2Bytes(Integer.parseInt(ips[1]), 2));


                                } else {
                                    ipbuff = BytesHelp.arrayApend(ipbuff, "000.000.000.000".getBytes());

                                    portbuff = BytesHelp.arrayApend(portbuff, BytesHelp.int2Bytes(0, 2));

                                }
                                //IP地址2
                                if (jsonData.containsKey("ip2")) {

                                    String ip = jsonData.getString("ip2");
                                    String[] ips = ip.split(":");
                                    String[] texts = ips[0].split("[.]");
                                    String newIp = String.format("%03d", Integer.parseInt(texts[0]));
                                    newIp += "." + String.format("%03d", Integer.parseInt(texts[1]));
                                    newIp += "." + String.format("%03d", Integer.parseInt(texts[2]));
                                    newIp += "." + String.format("%03d", Integer.parseInt(texts[3]));

                                    ipbuff = BytesHelp.arrayApend(ipbuff, newIp.getBytes());

                                    portbuff = BytesHelp.arrayApend(portbuff, BytesHelp.int2Bytes(Integer.parseInt(ips[1]), 2));
                                } else {
                                    ipbuff = BytesHelp.arrayApend(ipbuff, "000.000.000.000".getBytes());

                                    portbuff = BytesHelp.arrayApend(portbuff, BytesHelp.int2Bytes(0, 2));
                                }
                                //IP地址3
                                if (jsonData.containsKey("ip3")) {

                                    String ip = jsonData.getString("ip3");
                                    String[] ips = ip.split(":");
                                    String[] texts = ips[0].split("[.]");
                                    String newIp = String.format("%03d", Integer.parseInt(texts[0]));
                                    newIp += "." + String.format("%03d", Integer.parseInt(texts[1]));
                                    newIp += "." + String.format("%03d", Integer.parseInt(texts[2]));
                                    newIp += "." + String.format("%03d", Integer.parseInt(texts[3]));

                                    ipbuff = BytesHelp.arrayApend(ipbuff, newIp.getBytes());

                                    portbuff = BytesHelp.arrayApend(portbuff, BytesHelp.int2Bytes(Integer.parseInt(ips[1]), 2));
                                } else {
                                    ipbuff = BytesHelp.arrayApend(ipbuff, "000.000.000.000".getBytes());

                                    portbuff = BytesHelp.arrayApend(portbuff, BytesHelp.int2Bytes(0, 2));
                                }
                                //IP地址4
                                if (jsonData.containsKey("ip4")) {

                                    String ip = jsonData.getString("ip4");
                                    String[] ips = ip.split(":");
                                    String[] texts = ips[0].split("[.]");
                                    String newIp = String.format("%03d", Integer.parseInt(texts[0]));
                                    newIp += "." + String.format("%03d", Integer.parseInt(texts[1]));
                                    newIp += "." + String.format("%03d", Integer.parseInt(texts[2]));
                                    newIp += "." + String.format("%03d", Integer.parseInt(texts[3]));

                                    ipbuff = BytesHelp.arrayApend(ipbuff, newIp.getBytes());

                                    portbuff = BytesHelp.arrayApend(portbuff, BytesHelp.int2Bytes(Integer.parseInt(ips[1]), 2));
                                } else {
                                    ipbuff = BytesHelp.arrayApend(ipbuff, "000.000.000.000".getBytes());

                                    portbuff = BytesHelp.arrayApend(portbuff, BytesHelp.int2Bytes(0, 2));
                                }

                                dataContent = BytesHelp.arrayApend(dataContent, ipbuff);


                                dataContent = BytesHelp.arrayApend(dataContent, portbuff);


                                count += 60;
                                count += 8;

                                dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.subBytes(settingBuff, count, 44));

                                count += 44;
                                //pw
                                dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.hexStr2Bytes("0000"));

                                count += 2;

                                //tp
                                String tp = timeFormat.format(new Date());

                                dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.hexStr2Bytes(tp.substring(tp.length() - 2, tp.length())));
                                dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.hexStr2Bytes(tp.substring(tp.length() - 4, tp.length() - 2)));
                                dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.hexStr2Bytes(tp.substring(tp.length() - 6, tp.length() - 4)));
                                dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.hexStr2Bytes(tp.substring(tp.length() - 8, tp.length() - 6)));

                                dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.hexStr2Bytes("00"));


                                count += 5;


                                byte[] lenBuff = new byte[1];
                                //lenBuff[0] =  (byte) (dataContent.length() / 2);
                                // String content = "30" + rtuCode + "E7" + dataContent;
                                // byte[] buff = BytesHelp.hexStr2Bytes(content);
                                byte[] crc = new byte[1];
                                crc[0] = BytesHelp.GetCRCByte(dataContent);

                                lenBuff[0] = (byte) dataContent.length;
                                String datagram = "68" + BytesHelp.byte2HexStr(lenBuff) + "68" + BytesHelp.byte2HexStr(dataContent) + BytesHelp.byte2HexStr(crc) + "16";

                                byte[] datagrambuff = BytesHelp.hexStr2Bytes(datagram);

                                //  Date now = new Date();
                                String funcCode = "88";
//                                    CommandEntity entity = new CommandEntity();
//                                    entity.setDatagram(datagram);
//                                    entity.setRtuCode(rtuCode);
//                                    entity.setNeedTry(false);
//                                    entity.setTryCount(0);
//                                    entity.setCreateTime(now);
//                                    entity.setLiveTime(24 * 60);
//                                    entity.setFuncCode(funcCode);
//                                    entity.setTry(false);
                                LogHelper.info("Manage-" + rtuCode + "-" + datagram);

                                DataProcess.SubmitCommand(rtuCode, datagram, funcCode, true);
//                                    if (DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.containsKey(rtuCode)) {
//                                        LinkedBlockingQueue<CommandEntity> datagramlist = DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.get(rtuCode);
//                                        datagramlist.clear();
//                                        datagramlist.offer(entity);
//                                    } else {
//                                        LinkedBlockingQueue<CommandEntity> datagramlist = new LinkedBlockingQueue<>();
//                                        datagramlist.offer(entity);
//                                        DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.put(rtuCode, datagramlist);
//                                    }

                                DataProcess.DownloadNotify(rtuCode);

//                                    RestTemplate restTemplate = new RestTemplate();
//                                    JSONObject request = new JSONObject();
//                                    request.put("rtuCode", rtuCode);
//                                    JSONObject response = restTemplate.postForObject(new URI(config.getNotifyurl()), request, JSONObject.class);
//                                    if (response != null) {
//                                        if (response.getString("code").equals("0")) {
//                                            LogHelper.info("*****************  notify   try  download  datagram");
//                                            JSONObject responesBody = new JSONObject();
//                                            responesBody.put("msg", "指令已发送");
//                                            responesBody.put("code", "0");
//                                            return responesBody;
//                                        }
//                                    }

                            } else {
                                LogHelper.info("rtu setting error:" + rtuCode + "ip配置数量至少1个");
                            }

                        }

                        //    }

                    } else {
                        if (jsonData.containsKey("newRtuCode")) {
                            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                            String dataContent = "";
                            String v = jsonData.getString("newRtuCode");
                            dataContent += v;
                            dataContent += "0000";
                            String tp = timeFormat.format(new Date());
                            int count = tp.length();
                            dataContent += tp.substring(count - 2, count);
                            count -= 2;
                            dataContent += tp.substring(count - 2, count);
                            count -= 2;
                            dataContent += tp.substring(count - 2, count);
                            count -= 2;
                            dataContent += tp.substring(count - 2, count);
                            count -= 2;
                            dataContent += "00";
                            byte[] lenBuff = new byte[1];
                            String content = "30" + rtuCode + "10" + dataContent;
                            byte[] buff = BytesHelp.hexStr2Bytes(content);
                            byte[] crc = new byte[1];
                            crc[0] = BytesHelp.GetCRCByte(buff);
                            lenBuff[0] = (byte) buff.length;
                            String datagram = "68" + BytesHelp.byte2HexStr(lenBuff) + "68" + content + BytesHelp.byte2HexStr(crc) + "16";
                            byte[] datagrambuff = BytesHelp.hexStr2Bytes(datagram);
                            Date now = new Date();
                            String funcCode = "10";
                            LogHelper.info("Manage-" + rtuCode + "-" + datagram);
                            DataProcess.SubmitCommand(rtuCode, datagram, funcCode, true);
                            DataProcess.DownloadNotify(rtuCode);
                        } else {
                            String dataContent = "";
                            //IP地址1
                            if (jsonData.containsKey("ip1")) {
                                String v = jsonData.getString("ip1");
                                byte[] buff = BytesHelp.createSzyIpBytes((byte) 0x04, v);
                                dataContent += BytesHelp.byte2HexStr(buff);
                            }
                            //IP地址2
                            if (jsonData.containsKey("ip2")) {
                                String v = jsonData.getString("ip2");
                                byte[] buff = BytesHelp.createSzyIpBytes((byte) 0x06, v);
                                dataContent += BytesHelp.byte2HexStr(buff);
                            }
                            //IP地址3
                            if (jsonData.containsKey("ip3")) {
                                String v = jsonData.getString("ip3");
                                byte[] buff = BytesHelp.createSzyIpBytes((byte) 0x08, v);
                                dataContent += BytesHelp.byte2HexStr(buff);
                            }
                            //IP地址4
                            if (jsonData.containsKey("ip4")) {
                                String v = jsonData.getString("ip4");
                                byte[] buff = BytesHelp.createSzyIpBytes((byte) 0x0A, v);
                                dataContent += BytesHelp.byte2HexStr(buff);
                            }

                            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                            byte[] lenBuff = new byte[1];
                            //lenBuff[0] =  (byte) (dataContent.length() / 2);
                            String content = "30" + rtuCode + "E7" + dataContent;
                            byte[] buff = BytesHelp.hexStr2Bytes(content);
                            byte[] crc = new byte[1];
                            crc[0] = BytesHelp.GetCRCByte(buff);

                            lenBuff[0] = (byte) buff.length;
                            String datagram = "68" + BytesHelp.byte2HexStr(lenBuff) + "68" + content + BytesHelp.byte2HexStr(crc) + "16";

                            byte[] datagrambuff = BytesHelp.hexStr2Bytes(datagram);

                            Date now = new Date();
                            String funcCode = "E7";
//                        CommandEntity entity = new CommandEntity();
//                        entity.setDatagram(datagram);
//                        entity.setRtuCode(rtuCode);
//                        entity.setNeedTry(false);
//                        entity.setTryCount(0);
//                        entity.setCreateTime(now);
//                        entity.setLiveTime(24 * 60);
//                        entity.setFuncCode(funcCode);
//                        entity.setTry(false);
                            LogHelper.info("Manage-" + rtuCode + "-" + datagram);
                            DataProcess.SubmitCommand(rtuCode, datagram, funcCode, true);
//                        if (DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.containsKey(rtuCode)) {
//                            LinkedBlockingQueue<CommandEntity> datagramlist = DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.get(rtuCode);
//                            datagramlist.clear();
//                            datagramlist.offer(entity);
//                        } else {
//                            LinkedBlockingQueue<CommandEntity> datagramlist = new LinkedBlockingQueue<>();
//                            datagramlist.offer(entity);
//                            DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.put(rtuCode, datagramlist);
//                        }

                            DataProcess.DownloadNotify(rtuCode);
                        }


//                        RestTemplate restTemplate = new RestTemplate();
//                        JSONObject request = new JSONObject();
//                        request.put("rtuCode", rtuCode);
//                        JSONObject response = restTemplate.postForObject(new URI(config.getNotifyurl()), request, JSONObject.class);
//                        if (response != null) {
//                            if (response.getString("code").equals("0")) {
//                                LogHelper.info("*****************  notify   try  download  datagram");
                        JSONObject responesBody = new JSONObject();
                        responesBody.put("msg", "指令已发送");
                        responesBody.put("code", "0");
                        return responesBody;
//                            }
//                        }
                    }
                } else {
                    LogHelper.info("dont know agreement");
                    JSONObject responesBody = new JSONObject();
                    responesBody.put("msg", "测站没设置规约");
                    responesBody.put("code", "1");
                    return responesBody;
                }
            } else {
                LogHelper.info("dont know agreement");
                JSONObject responesBody = new JSONObject();
                responesBody.put("msg", "测站没设置规约");
                responesBody.put("code", "1");
                return responesBody;
            }
        } catch (Exception e) {
            LogHelper.error(e);
            result.put("code", "1");
        }
        return result;
    }


    /**
     * 查询运行配置参数
     *
     * @param rtuCode
     * @return
     */
    @GetMapping(value = "DataCollectServer/Manage/Rtu/Setting/Run/{rtuCode}")
    @ResponseBody
    public Object GetRtuSettingRun(@PathVariable(name = "rtuCode") String rtuCode) {
        try {
            JSONObject respones = new JSONObject();
            respones.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
            RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
            HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
            if (opsHash.hasKey(rtuCode, GBConstants.BASE_KEY_AGREEMENT)) {
                String agreement = opsHash.get(rtuCode, GBConstants.BASE_KEY_AGREEMENT);
                if (agreement.equals(GBConstants.AGREEMENT_KIND_SW)) {
                    SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                    String content = "2010" + "2110" + "2210" + "2320" + "2410" + "2710" + "283B" + "302B" + "3810" + "4010" + "4110" + "4210" + "4310" + "4410";
                    //content +="0D40" + "0120" + "0280" + "0310" + "0C08" + "0D40" + "0F00" + "1008" + "1208";
                    String datagram = "7E7E";
                    datagram += rtuCode;
                    datagram += "01";
                    datagram += "0000";
                    datagram += "43";
                    //报文长度
                    byte[] bodyBuff = BytesHelp.int2Bytes(content.length() / 2 + 2 + 6, 2);
                    datagram += "8" + BytesHelp.byte2HexStr(bodyBuff).substring(1);
                    datagram += "02";//起始符
                    datagram += "0001";//流水号
                    datagram += timeFormat.format(new Date()).substring(2);//发报时间
                    datagram += content;
                    //结束符
                    datagram += "05";
                    byte[] buff = BytesHelp.hexStr2Bytes(datagram);
                    byte[] crc16 = BytesHelp.crcFun2014(buff);
                    byte[] datagrambuff = BytesHelp.arrayApend(buff, crc16);//CRC16

                    // Date now = new Date();

                    datagram = BytesHelp.byte2HexStr(datagrambuff);
                    String funcCode = "43";
//                    CommandEntity entity = new CommandEntity();
//                    entity.setDatagram(datagram);
//                    entity.setRtuCode(rtuCode);
//                    entity.setNeedTry(false);
//                    entity.setTryCount(0);
//                    entity.setCreateTime(now);
//                    entity.setLiveTime(24 * 60);
//                    entity.setFuncCode(funcCode);
//                    entity.setTry(false);
                    LogHelper.info("Manage-" + rtuCode + "-" + datagram);
                    DataProcess.SubmitCommand(rtuCode, datagram, funcCode);
//                    if (DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.containsKey(rtuCode)) {
//                        LinkedBlockingQueue<CommandEntity> datagramlist = DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.get(rtuCode);
//                        datagramlist.clear();
//                        datagramlist.offer(entity);
//                    } else {
//                        LinkedBlockingQueue<CommandEntity> datagramlist = new LinkedBlockingQueue<>();
//                        datagramlist.offer(entity);
//                        DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.put(rtuCode, datagramlist);
//                    }

//                    RestTemplate restTemplate = new RestTemplate();
//                    JSONObject request = new JSONObject();
//                    request.put("rtuCode", rtuCode);
//                    JSONObject sendresponse = restTemplate.postForObject(new URI(config.getNotifyurl()), request, JSONObject.class);
//                    if (sendresponse != null) {
//                        if (sendresponse.getString("code").equals("0")) {
//                            LogHelper.info("*****************  notify   try  download  datagram");
//                        }
//                    }

                    DataProcess.DownloadNotify(rtuCode);

                    respones.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);
                    return respones;
                } else if (agreement.equals(GBConstants.AGREEMENT_KIND_SZY)) {
                    String datagram = DataTemplateSzyC53.createDatagram(rtuCode);
                    if (null != datagram) {
                        Date now = new Date();
                        String funcCode = "53";
//                        CommandEntity entity = new CommandEntity();
//                        entity.setDatagram(datagram);
//                        entity.setRtuCode(rtuCode);
//                        entity.setNeedTry(false);
//                        entity.setTryCount(0);
//                        entity.setCreateTime(now);
//                        entity.setLiveTime(24 * 60);
//                        entity.setFuncCode(funcCode);
//                        entity.setTry(false);
                        LogHelper.info("Manage-" + rtuCode + "-" + datagram);
//                        if (DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.containsKey(rtuCode)) {
//                            LinkedBlockingQueue<CommandEntity> datagramlist = DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.get(rtuCode);
//                            datagramlist.clear();
//                            datagramlist.offer(entity);
//                        } else {
//                            LinkedBlockingQueue<CommandEntity> datagramlist = new LinkedBlockingQueue<>();
//                            datagramlist.offer(entity);
//                            DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.put(rtuCode, datagramlist);
//                        }

                        DataProcess.SubmitCommand(rtuCode, datagram, funcCode);

                        DataProcess.DownloadNotify(rtuCode);
//                        RestTemplate restTemplate = new RestTemplate();
//                        JSONObject request = new JSONObject();
//                        request.put("rtuCode", rtuCode);
//                        JSONObject response = restTemplate.postForObject(new URI(config.getNotifyurl()), request, JSONObject.class);
//                        if (response != null) {
//                            if (response.getString("code").equals("0")) {
//                                LogHelper.info("*****************  notify   try  download  datagram");
//                                JSONObject responesBody = new JSONObject();
//                                responesBody.put("msg", "指令已发送");
//                                responesBody.put("code", "0");
//                                return responesBody;
//                            }
//                        }
                    } else {
                        LogHelper.info(rtuCode + " 报文产生失败");
                    }
                } else {
                    LogHelper.info("dont know agreement");
                    JSONObject responesBody = new JSONObject();
                    responesBody.put("msg", "测站没设置规约");
                    responesBody.put("code", "1");
                    return responesBody;
                }
            } else {
                LogHelper.info("dont know agreement");
                JSONObject responesBody = new JSONObject();
                responesBody.put("msg", "测站没设置规约");
                responesBody.put("code", "1");
                return responesBody;
            }
        } catch (Exception e) {
            LogHelper.error(e);
        }
        return null;
    }

    /**
     * 设置RTU运行参数
     *
     * @param jsonData
     */
    @PostMapping(value = "DataCollectServer/Manage/Rtu/RunSetting")
    public JSONObject RtuRunSetting(@RequestBody JSONObject jsonData) {

        try {
            JSONObject respones = new JSONObject();

            String rtuCode = jsonData.getString("rtuCode");

            respones.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
            RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
            HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
            if (opsHash.hasKey(rtuCode, GBConstants.BASE_KEY_AGREEMENT)) {
                String agreement = opsHash.get(rtuCode, GBConstants.BASE_KEY_AGREEMENT);
                if (agreement.equals(GBConstants.AGREEMENT_KIND_SW)) {

                    String dataContent = "";
                    //定时报时间间隔
                    if (jsonData.containsKey("intervalTime")) {
                        String v = jsonData.getString("intervalTime");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x20, v, 0, 1);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    //加报时间间隔
                    if (jsonData.containsKey("addIntervalTime")) {
                        String v = jsonData.getString("addIntervalTime");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x21, v, 0, 1);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    //日降水量起始时间
                    if (jsonData.containsKey("rainTime")) {
                        String v = jsonData.getString("rainTime");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x22, v, 0, 1);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    //采样间隔
                    if (jsonData.containsKey("collectInterval")) {
                        String v = jsonData.getString("collectInterval");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x23, v, 0, 2);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    //数据存储间隔
                    if (jsonData.containsKey("dataSaveInterval")) {
                        String v = jsonData.getString("dataSaveInterval");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x24, v, 0, 1);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    //雨量加报阀值
                    if (jsonData.containsKey("rainAddValue")) {
                        String v = jsonData.getString("rainAddValue");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x27, v, 0, 1);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    //水位基值
                    if (jsonData.containsKey("waterLevelBase")) {
                        String v = jsonData.getString("waterLevelBase");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x28, v, 3, 4);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    //水位修正基值
                    if (jsonData.containsKey("waterLevelCorrectValue")) {
                        String v = jsonData.getString("waterLevelCorrectValue");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x30, v, 3, 3);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    //加报水位
                    if (jsonData.containsKey("addWaterLevel")) {
                        String v = jsonData.getString("addWaterLevel");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x38, v, 2, 2);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    //水位以上加报阀值
                    if (jsonData.containsKey("addWaterUpValue")) {
                        String v = jsonData.getString("addWaterUpValue");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x40, v, 2, 2);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    //水位以下加报阀值
                    if (jsonData.containsKey("addWaterDownValue")) {
                        String v = jsonData.getString("addWaterDownValue");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x41, v, 2, 2);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    //流量加报阀值
                    if (jsonData.containsKey("flowValue")) {
                        String v = jsonData.getString("flowValue");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x42, v, 3, 3);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    //流速加报阀值
                    if (jsonData.containsKey("flowSpeetValue")) {
                        String v = jsonData.getString("flowSpeetValue");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x43, v, 3, 3);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    //闸位加报阀值
                    if (jsonData.containsKey("waterGateValue")) {
                        String v = jsonData.getString("waterGateValue");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x44, v, 2, 2);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }

                    String datagram = "7E7E";
                    datagram += rtuCode;
                    datagram += "01";
                    datagram += "0000";
                    datagram += "42";
                    //报文长度
                    byte[] bodyBuff = BytesHelp.int2Bytes(dataContent.length() / 2 + 2 + 6, 2);
                    datagram += "8" + BytesHelp.byte2HexStr(bodyBuff).substring(1);
                    datagram += "02";//起始符
                    datagram += "0001";//流水号
                    SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                    datagram += timeFormat.format(new Date()).substring(2);//发报时间
                    datagram += dataContent;
                    //结束符
                    datagram += "05";
                    byte[] buff = BytesHelp.hexStr2Bytes(datagram);
                    byte[] crc16 = BytesHelp.crcFun2014(buff);
                    byte[] datagrambuff = BytesHelp.arrayApend(buff, crc16);//CRC16

                    Date now = new Date();

                    datagram = BytesHelp.byte2HexStr(datagrambuff);
                    String funcCode = "42";
//                    CommandEntity entity = new CommandEntity();
//                    entity.setDatagram(datagram);
//                    entity.setRtuCode(rtuCode);
//                    entity.setNeedTry(false);
//                    entity.setTryCount(0);
//                    entity.setCreateTime(now);
//                    entity.setLiveTime(24 * 60);
//                    entity.setFuncCode(funcCode);
//                    entity.setTry(false);
                    LogHelper.info("Manage-" + rtuCode + "-" + datagram);
//                    if (DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.containsKey(rtuCode)) {
//                        LinkedBlockingQueue<CommandEntity> datagramlist = DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.get(rtuCode);
//                        datagramlist.clear();
//                        datagramlist.offer(entity);
//                    } else {
//                        LinkedBlockingQueue<CommandEntity> datagramlist = new LinkedBlockingQueue<>();
//                        datagramlist.offer(entity);
//                        DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.put(rtuCode, datagramlist);
//                    }
                    DataProcess.SubmitCommand(rtuCode, datagram, funcCode, true);
//                    RestTemplate restTemplate = new RestTemplate();
//                    JSONObject request = new JSONObject();
//                    request.put("rtuCode", rtuCode);
//                    JSONObject sendresponse = restTemplate.postForObject(new URI(config.getNotifyurl()), request, JSONObject.class);
//                    if (sendresponse != null) {
//                        if (sendresponse.getString("code").equals("0")) {
//                            LogHelper.info("*****************  notify   try  download  datagram");
//                        }
//                    }
                    DataProcess.DownloadNotify(rtuCode);
                    respones.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);
                    return respones;
                } else if (agreement.equals(GBConstants.AGREEMENT_KIND_SZY)) {

                    String datagram = DataTemplateSzyCA1.createDatagram(rtuCode, jsonData);
                    if (null != datagram) {
                        //Date now = new Date();
                        String funcCode = "A1";
//                        CommandEntity entity = new CommandEntity();
//                        entity.setDatagram(datagram);
//                        entity.setRtuCode(rtuCode);
//                        entity.setNeedTry(false);
//                        entity.setTryCount(0);
//                        entity.setCreateTime(now);
//                        entity.setLiveTime(24 * 60);
//                        entity.setFuncCode(funcCode);
//                        entity.setTry(false);
                        LogHelper.info("Manage-" + rtuCode + "-" + datagram);
//                        if (DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.containsKey(rtuCode)) {
//                            LinkedBlockingQueue<CommandEntity> datagramlist = DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.get(rtuCode);
//                            datagramlist.clear();
//                            datagramlist.offer(entity);
//                        } else {
//                            LinkedBlockingQueue<CommandEntity> datagramlist = new LinkedBlockingQueue<>();
//                            datagramlist.offer(entity);
//                            DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.put(rtuCode, datagramlist);
//                        }

                        DataProcess.SubmitCommand(rtuCode, datagram, funcCode, true);


//                        RestTemplate restTemplate = new RestTemplate();
//                        JSONObject request = new JSONObject();
//                        request.put("rtuCode", rtuCode);
//                        JSONObject sendresponse = restTemplate.postForObject(new URI(config.getNotifyurl()), request, JSONObject.class);
//                        if (sendresponse != null) {
//                            if (sendresponse.getString("code").equals("0")) {
//                                LogHelper.info("*****************  notify   try  download  datagram");
//                                JSONObject responesBody = new JSONObject();
//                                responesBody.put("msg", "指令已发送");
//                                responesBody.put("code", "0");
//                                return responesBody;
//                            }
//                        }
                        DataProcess.DownloadNotify(rtuCode);
                    } else {
                        LogHelper.info(rtuCode + " 报文产生失败");
                    }
                } else {
                    LogHelper.info("dont know agreement");
                    JSONObject responesBody = new JSONObject();
                    responesBody.put("msg", "测站没设置规约");
                    responesBody.put("code", "1");
                    return responesBody;
                }
            } else {
                LogHelper.info("dont know agreement");
                JSONObject responesBody = new JSONObject();
                responesBody.put("msg", "测站没设置规约");
                responesBody.put("code", "1");
                return responesBody;
            }
        } catch (Exception e) {
            LogHelper.error(e);
        }
        return null;


    }


    /**
     * 给单个RTU发送指令
     *
     * @param jsonData
     * @return
     */
    @PostMapping(value = "DataCollectServer/Manage/Command")
    public JSONObject submitRtuCommand(@RequestBody JSONObject jsonData) {
        JSONObject result = new JSONObject();
        try {
            Date now = new Date();
            String rtucode = jsonData.getString("rtucode");
            String datagram = jsonData.getString("datagram");
            String funcCode = jsonData.getString("funcCode");
//            CommandEntity entity = new CommandEntity();
//            entity.setDatagram(datagram);
//            entity.setRtuCode(rtucode);
//            entity.setNeedTry(false);
//            entity.setTryCount(0);
//            entity.setCreateTime(now);
//            entity.setLiveTime(24 * 60);
//            entity.setFuncCode(funcCode);
//            entity.setTry(false);

            LogHelper.info("Manage-" + rtucode + "-" + datagram);
            if (funcCode.equals("F3")) {
                this.RtuReboot(rtucode);
            } else if (funcCode.equals("88") || funcCode.equals("E7") || funcCode.equals("A1")) {
                DataProcess.SubmitCommand(rtucode, datagram, funcCode, true);
            } else {
                DataProcess.SubmitCommand(rtucode, datagram, funcCode);
            }


//            if (DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.containsKey(rtucode)) {
//                LinkedBlockingQueue<CommandEntity> datagramlist = DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.get(rtucode);
//                datagramlist.clear();
//                datagramlist.offer(entity);
//            } else {
//                LinkedBlockingQueue<CommandEntity> datagramlist = new LinkedBlockingQueue<>();
//                datagramlist.offer(entity);
//                DataProcessHolder.newInstance().dataProcess.relpayCommandToRtu.put(rtucode, datagramlist);
//            }
//            JSONObject response = null;
//            try {
//                RestTemplate restTemplate = new RestTemplate();
//                JSONObject request = new JSONObject();
//                request.put("rtuCode", rtucode);
//                response = restTemplate.postForObject(new URI(config.getNotifyurl()), request, JSONObject.class);
//                if (response != null) {
//                    if (response.getString("code").equals("0")) {
//                        LogHelper.info("*****************  notify   try  download  datagram");
//                    }
//                }
//            } catch (URISyntaxException e) {
//                e.printStackTrace();
//            }

            DataProcess.DownloadNotify(rtucode);
            result.put("code", "0");
        } catch (Exception e) {
            LogHelper.error(e);
            result.put("code", "1");
        }
        return result;
    }


    /**
     * 发送文件到rtu
     *
     * @param jsonData
     * @return
     */
    @PostMapping(value = "DataCollectServer/Manage/Rtu/File")
    public JSONObject submitRtuFile(@RequestBody JSONObject jsonData) {
        JSONObject responesBody = new JSONObject();
        try {
            responesBody.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
            RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
            HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
            String rtuCode = jsonData.getString(GBConstants.BASE_KEY_RTU);
            if (opsHash.hasKey(rtuCode, GBConstants.BASE_KEY_AGREEMENT)) {
                String agreement = opsHash.get(rtuCode, GBConstants.BASE_KEY_AGREEMENT);
                if (agreement.equals(GBConstants.AGREEMENT_KIND_SW)) {
                    if (this.UploadSwFile(jsonData)) {
                        responesBody.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);
                    }
                } else if (agreement.equals(GBConstants.AGREEMENT_KIND_SZY)) {
                    if (this.UploadSzyFile(jsonData)) {
                        responesBody.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);
                    }
                } else {
                    LogHelper.info("dont know agreement");
                    responesBody.put("msg", "测站没设置规约");
                }
            } else {
                LogHelper.info("dont know agreement");
                responesBody.put("msg", "测站没设置规约");
            }
        } catch (Exception e) {
            LogHelper.error(e);
        }
        return responesBody;
    }

    private boolean UploadSzyFile(JSONObject jsonData) {
        try {
            Date now = new Date();
            String datagram = jsonData.getString("dataGram");
            String rtucode = jsonData.getString("rtuCode");
            String binFileName = jsonData.getString("binFile");
            String configFileName = jsonData.getString("configFile");
            String savePath = jsonData.getString("savePath");
            DataProcess.ClearCommand(rtucode, GBConstants.REDIS_KEY_COMMAND_FILE);
           // BASE64Decoder decoder = new BASE64Decoder();
          //  byte[] databuff =  decoder.decodeBuffer(datagram);
            byte[] databuff =Base64.getDecoder().decode(datagram);
            String batchId = UUID.randomUUID().toString().replace("-", "").toLowerCase();
            int index = 1;
            int count = 0;
            int total = databuff.length / 1024;
            if (databuff.length > total * 1024) {
                total += 1;
            }
            while (count < databuff.length) {
                int len = 0;
                if (databuff.length - count > 1024) {
                    len = 1024;
                } else {
                    len = databuff.length - count;
                }
                byte[] tempBuf = new byte[len];
                System.arraycopy(databuff, count, tempBuf, 0, len);
                byte[] respPacket_h = BytesHelp.hexStr2Bytes("680068");  //帧起始符
                byte[] respPacket = BytesHelp.hexStr2Bytes("30");//中心站地址
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes(rtucode));//遥测站地址
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("F1"));//密码
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.int2Bytes(index, 2));
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.int2Bytes(total, 2));
                int datacontentLen = 0;
                if (index == 1) {
                    datacontentLen += 1 + savePath.length() + binFileName.length();
                    datacontentLen += tempBuf.length;
                } else {
                    datacontentLen += tempBuf.length;
                }
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.int2Bytes(datacontentLen, 2));
                if (index == 1) {
                    byte[] filenamebuff = BytesHelp.arrayApend(savePath.getBytes(), binFileName.getBytes());
                    respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.int2Bytes(filenamebuff.length, 1));
                    respPacket = BytesHelp.arrayApend(respPacket, filenamebuff);
                }
                respPacket = BytesHelp.arrayApend(respPacket, tempBuf);
                byte[] crc = new byte[1]; //系统计算的校验码
                crc[0] = BytesHelp.GetCRCByte(respPacket);
                respPacket = BytesHelp.arrayApend(respPacket_h, respPacket);
                respPacket = BytesHelp.arrayApend(respPacket, crc);//CRC16
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("16"));
                CommandEntity entity = new CommandEntity();
                entity.setDatagram(BytesHelp.byte2HexStr(respPacket));
                entity.setRtuCode(rtucode);
                entity.setNeedTry(true);
                entity.setTryCount(0);
                entity.setCreateTime(now);
                entity.setWaittingBack(true);
                entity.setLiveTime(24 * 60);
                entity.setFuncCode("F1");
                entity.setTry(false);
                entity.setBatchId(batchId);
                entity.setKey(Integer.toString(index));
                DataProcess.SubmitFileCommand(entity);
                index += 1;
                count += len;
            }
            RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
            HashOperations<String, String, String> ops = redisTemplate.opsForHash();
            JSONObject downFileBody = new JSONObject();
            downFileBody.put("fileName", binFileName);
            downFileBody.put("fileBlockSize", total);
            ops.put(rtucode, "toRtuFileInfo", downFileBody.toJSONString());
            DataProcess.DownloadNotify(rtucode);
            return true;
        } catch (Exception e) {
            LogHelper.error(e);
        }
        return false;
    }

    private boolean UploadSwFile(JSONObject jsonData) {
        try {
            Date now = new Date();
            String datagram = jsonData.getString("dataGram");
            String rtucode = jsonData.getString("rtuCode");
            String binFileName = jsonData.getString("binFile");
            String savePath = jsonData.getString("savePath");

            DataProcess.ClearCommand(rtucode, GBConstants.REDIS_KEY_COMMAND_FILE);

           // BASE64Decoder decoder = new BASE64Decoder();
            byte[] databuff =Base64.getDecoder().decode(datagram);
            //byte[] databuff = decoder.decodeBuffer(datagram);
            String batchId = UUID.randomUUID().toString().replace("-", "").toLowerCase();
            int index = 1;
            int count = 0;
            int total = databuff.length / 1024;
            if (databuff.length > total * 1024) {
                total += 1;
            }
            while (count < databuff.length) {
                int len = 0;
                if (databuff.length - count > 1024) {
                    len = 1024;
                } else {
                    len = databuff.length - count;
                }
                byte[] tempBuf = new byte[len];
                System.arraycopy(databuff, count, tempBuf, 0, len);
                byte[] respPacket = BytesHelp.hexStr2Bytes("7E7E");  //帧起始符
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes(rtucode));//遥测站地址
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("01"));//中心站地址
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("0000"));//密码
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("F1"));//功能码
                int datacontentLen = 0;
                if (index == 1) {
                    datacontentLen += 14;
                    datacontentLen += 1 + savePath.length() + binFileName.length();
                    datacontentLen += tempBuf.length;
                } else {
                    datacontentLen += 14;
                    datacontentLen += tempBuf.length;
                }
                String dflag = BytesHelp.byte2HexStr(BytesHelp.int2Bytes(datacontentLen, 2));
                dflag = "8" + dflag.substring(1, dflag.length());
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes(dflag)); //报文下行标识及长度
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("02"));//报文起始符
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("0001"));//流水号
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.getFBTm());//发报时间
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.int2Bytes(index, 2));
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.int2Bytes(total, 2));
                datacontentLen = 0;
                if (index == 1) {
                    datacontentLen += 1 + savePath.length() + binFileName.length();
                    datacontentLen += tempBuf.length;
                } else {
                    datacontentLen += tempBuf.length;
                }
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.int2Bytes(datacontentLen, 2));
                if (index == 1) {
                    byte[] filenamebuff = BytesHelp.arrayApend(savePath.getBytes(), binFileName.getBytes());
                    respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.int2Bytes(filenamebuff.length, 1));
                    respPacket = BytesHelp.arrayApend(respPacket, filenamebuff);
                }
                respPacket = BytesHelp.arrayApend(respPacket, tempBuf);
                if (index == 1) {
                    respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("05"));//RTU2014年报文正文结束符
                } else if (index + 1 == total) {
                    respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("03"));//RTU2014年报文正文结束符
                } else {
                    respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("17"));//RTU2014年报文正文结束符
                }
                byte[] crc16 = BytesHelp.crcFun2014(respPacket);
                respPacket = BytesHelp.arrayApend(respPacket, crc16);//CRC16
                CommandEntity entity = new CommandEntity();
                entity.setDatagram(BytesHelp.byte2HexStr(respPacket));
                entity.setRtuCode(rtucode);
                entity.setNeedTry(true);
                entity.setTryCount(0);
                entity.setFuncCode("F1");
                entity.setWaittingBack(true);
                entity.setCreateTime(now);
                entity.setLiveTime(24 * 60);
                entity.setTry(false);
                entity.setBatchId(batchId);
                entity.setKey(Integer.toString(index));
                DataProcess.SubmitFileCommand(entity);
                index += 1;
                count += len;
            }
            RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
            HashOperations<String, String, String> ops = redisTemplate.opsForHash();
            JSONObject downFileBody = new JSONObject();
            downFileBody.put("fileName", binFileName);
            downFileBody.put("fileBlockSize", total);
            ops.put(rtucode, "toRtuFileInfo", downFileBody.toJSONString());

            DataProcess.DownloadNotify(rtucode);
            return true;
        } catch (Exception e) {
            LogHelper.error(e);
        }
        return false;
    }


    @PostMapping(value = "DataCollectServer/Manage/Rtu/BinFile")
    @ResponseBody
    public JSONObject submitRtuBinFile(@RequestBody JSONObject jsonData) {
        JSONObject responesBody = new JSONObject();
        try {
            responesBody.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
            RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
            HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
            String rtuCode = jsonData.getString(GBConstants.BASE_KEY_RTU);
            if (opsHash.hasKey(rtuCode, GBConstants.BASE_KEY_AGREEMENT)) {
                String agreement = opsHash.get(rtuCode, GBConstants.BASE_KEY_AGREEMENT);
                if (agreement.equals(GBConstants.AGREEMENT_KIND_SW)) {
                    if (this.UpdateSwRtu(jsonData)) {
                        responesBody.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);
                    }
                } else if (agreement.equals(GBConstants.AGREEMENT_KIND_SZY)) {
                    if (this.UpdateSzyRtu(jsonData)) {
                        responesBody.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);
                    }
                } else {
                    LogHelper.info("dont know agreement");
                    responesBody.put("msg", "测站没设置规约");
                }
            } else {
                LogHelper.info("dont know agreement");
                responesBody.put("msg", "测站没设置规约");
            }
        } catch (Exception e) {
            LogHelper.error(e);
        }
        return responesBody;
    }

    private boolean UpdateSzyRtu(JSONObject jsonData) {
        try {
            Date now = new Date();
            String datagram = jsonData.getString("dataGram");
            String rtucode = jsonData.getString("rtuCode");
            String binFileName = jsonData.getString("binFile");
            String configFileName = jsonData.getString("configFile");
            String savePath = jsonData.getString("savePath");
            DataProcess.ClearCommand(rtucode, GBConstants.REDIS_KEY_COMMAND_FILE);

            //BASE64Decoder decoder = new BASE64Decoder();
            //byte[] databuff = decoder.decodeBuffer(datagram);
            byte[] databuff =Base64.getDecoder().decode(datagram);
            String batchId = UUID.randomUUID().toString().replace("-", "").toLowerCase();
            int index = 1;
            int count = 0;
            int total = databuff.length / 1024;
            if (databuff.length > total * 1024) {
                total += 1;
            }
            while (count < databuff.length) {
                int len = 0;
                if (databuff.length - count > 1024) {
                    len = 1024;
                } else {
                    len = databuff.length - count;
                }
                byte[] tempBuf = new byte[len];
                System.arraycopy(databuff, count, tempBuf, 0, len);
                byte[] respPacket_h = BytesHelp.hexStr2Bytes("680068");  //帧起始符
                byte[] respPacket = BytesHelp.hexStr2Bytes("30");//中心站地址
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes(rtucode));//遥测站地址
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("F1"));//密码
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.int2Bytes(index, 2));
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.int2Bytes(total, 2));
                int datacontentLen = 0;
                if (index == 1) {
                    datacontentLen += 1 + savePath.length() + binFileName.length();
                    datacontentLen += tempBuf.length;
                } else {
                    datacontentLen += tempBuf.length;
                }
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.int2Bytes(datacontentLen, 2));
                if (index == 1) {
                    byte[] filenamebuff = BytesHelp.arrayApend(savePath.getBytes(), binFileName.getBytes());
                    respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.int2Bytes(filenamebuff.length, 1));
                    respPacket = BytesHelp.arrayApend(respPacket, filenamebuff);
                }
                respPacket = BytesHelp.arrayApend(respPacket, tempBuf);
                byte[] crc = new byte[1]; //系统计算的校验码
                crc[0] = BytesHelp.GetCRCByte(respPacket);
                respPacket = BytesHelp.arrayApend(respPacket_h, respPacket);
                respPacket = BytesHelp.arrayApend(respPacket, crc);//CRC16
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("16"));
                CommandEntity entity = new CommandEntity();
                entity.setDatagram(BytesHelp.byte2HexStr(respPacket));
                entity.setRtuCode(rtucode);
                entity.setNeedTry(true);
                entity.setTryCount(0);
                entity.setCreateTime(now);
                entity.setFuncCode("F1");
                entity.setWaittingBack(true);
                entity.setLiveTime(24 * 60);
                entity.setTry(false);
                entity.setBatchId(batchId);
                entity.setKey(Integer.toString(index));
                DataProcess.SubmitFileCommand(entity);
                index += 1;
                count += len;
            }

            RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
            HashOperations<String, String, String> ops = redisTemplate.opsForHash();
            JSONObject downFileBody = new JSONObject();
            downFileBody.put("fileName", binFileName);
            downFileBody.put("fileBlockSize", total);
            ops.put(rtucode, "toRtuFileInfo", downFileBody.toJSONString());

            //配置文件报文
            byte[] binFileCrc16 = BytesHelp.crcFun2014(databuff);
            String configStr = "LEVEL:2";
            byte[] configHc = new byte[]{0x0d, 0x0a};
            byte[] configBytes = configStr.getBytes();
            configBytes = BytesHelp.arrayApend(configBytes, configHc);
            int c1 = binFileCrc16[0] < 0 ? binFileCrc16[0] + 256 : binFileCrc16[0];
            int c2 = binFileCrc16[1] < 0 ? binFileCrc16[1] + 256 : binFileCrc16[1];
            configStr = "CRC16:" + String.format("%03d", c1) + "," + String.format("%03d", c2);
            configBytes = BytesHelp.arrayApend(configBytes, configStr.getBytes());
            configBytes = BytesHelp.arrayApend(configBytes, configHc);
            configStr = "CNT:0";
            configBytes = BytesHelp.arrayApend(configBytes, configStr.getBytes());
            configBytes = BytesHelp.arrayApend(configBytes, configHc);
            configStr = "RES:1";
            configBytes = BytesHelp.arrayApend(configBytes, configStr.getBytes());
            configBytes = BytesHelp.arrayApend(configBytes, configHc);
            configStr = "VER:" + binFileName;
            configBytes = BytesHelp.arrayApend(configBytes, configStr.getBytes());
            configBytes = BytesHelp.arrayApend(configBytes, configHc);
            String configpath = savePath + "config.txt";
            byte[] configPacket = BytesHelp.hexStr2Bytes("30");//中心站地址
            configPacket = BytesHelp.arrayApend(configPacket, BytesHelp.hexStr2Bytes(rtucode));//遥测站地址
            configPacket = BytesHelp.arrayApend(configPacket, BytesHelp.hexStr2Bytes("F4"));//功能码
            int datacontentLen = 0;
            datacontentLen += 14;
            datacontentLen += 1 + configpath.length();
            datacontentLen += configBytes.length;
            configPacket = BytesHelp.arrayApend(configPacket, BytesHelp.int2Bytes(1, 2));
            configPacket = BytesHelp.arrayApend(configPacket, BytesHelp.int2Bytes(1, 2));
            datacontentLen = 0;
            datacontentLen += 1 + configpath.length();
            datacontentLen += configBytes.length;
            configPacket = BytesHelp.arrayApend(configPacket, BytesHelp.int2Bytes(datacontentLen, 2));
            byte[] configfilenamebuff = configpath.getBytes();
            configPacket = BytesHelp.arrayApend(configPacket, BytesHelp.int2Bytes(configfilenamebuff.length, 1));
            configPacket = BytesHelp.arrayApend(configPacket, configfilenamebuff);
            configPacket = BytesHelp.arrayApend(configPacket, configBytes);
            byte[] crc = new byte[1]; //系统计算的校验码
            crc[0] = BytesHelp.GetCRCByte(configPacket);
            byte[] configPacket_h = BytesHelp.hexStr2Bytes("680068");  //帧起始符
            configPacket_h[1] = (byte) configPacket.length;
            configPacket = BytesHelp.arrayApend(configPacket_h, configPacket);
            configPacket = BytesHelp.arrayApend(configPacket, crc);//CRC16
            configPacket = BytesHelp.arrayApend(configPacket, BytesHelp.hexStr2Bytes("16"));
            CommandEntity configentity = new CommandEntity();
            configentity.setDatagram(BytesHelp.byte2HexStr(configPacket));
            configentity.setRtuCode(rtucode);
            configentity.setNeedTry(true);
            configentity.setTryCount(0);
            configentity.setCreateTime(now);
            configentity.setLiveTime(24 * 60);
            configentity.setFuncCode("F4");
            configentity.setWaittingBack(false);
            configentity.setTry(false);
            configentity.setBatchId(batchId);
            configentity.setKey(Integer.toString(1));
            DataProcess.SubmitFileCommand(configentity);

            //RTU重启指令
            byte[] respPacket_h = BytesHelp.hexStr2Bytes("680768");  //帧起始符
            byte[] respPacket = BytesHelp.hexStr2Bytes("30");//中心站地址
            respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes(rtucode));//遥测站地址
            respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("F3"));//功能码
            crc = new byte[1]; //系统计算的校验码
            crc[0] = BytesHelp.GetCRCByte(respPacket);
            respPacket = BytesHelp.arrayApend(respPacket_h, respPacket);
            respPacket = BytesHelp.arrayApend(respPacket, crc);//CRC
            respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("16"));
            CommandEntity entity = new CommandEntity();
            entity.setDatagram(BytesHelp.byte2HexStr(respPacket));
            entity.setRtuCode(rtucode);
            entity.setNeedTry(false);
            entity.setTryCount(0);
            entity.setCreateTime(new Date());
            entity.setLiveTime(24 * 60);
            entity.setFuncCode("F3");
            entity.setTry(false);
            entity.setWaittingBack(true);
            entity.setBatchId(batchId);
            DataProcess.SubmitFileCommand(entity);

            return true;
        } catch (Exception e) {
            LogHelper.error(e);
        }
        return false;
    }

    private boolean UpdateSwRtu(JSONObject jsonData) {
        try {
            Date now = new Date();
            String datagram = jsonData.getString("dataGram");
            String rtucode = jsonData.getString("rtuCode");
            String binFileName = jsonData.getString("binFile");
            String configFileName = jsonData.getString("configFile");
            String savePath = jsonData.getString("savePath");

            DataProcess.ClearCommand(rtucode, GBConstants.REDIS_KEY_COMMAND_FILE);

            //BASE64Decoder decoder = new BASE64Decoder();
            //byte[] databuff = decoder.decodeBuffer(datagram);
            byte[] databuff =Base64.getDecoder().decode(datagram);
            String batchId = UUID.randomUUID().toString().replace("-", "").toLowerCase();
            int index = 1;
            int count = 0;
            int total = databuff.length / 1024;
            if (databuff.length > total * 1024) {
                total += 1;
            }
            while (count < databuff.length) {
                int len = 0;
                if (databuff.length - count > 1024) {
                    len = 1024;
                } else {
                    len = databuff.length - count;
                }
                byte[] tempBuf = new byte[len];
                System.arraycopy(databuff, count, tempBuf, 0, len);
                byte[] respPacket = BytesHelp.hexStr2Bytes("7E7E");  //帧起始符
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes(rtucode));//遥测站地址
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("01"));//中心站地址
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("0000"));//密码
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("F1"));//功能码
                int datacontentLen = 0;
                if (index == 1) {
                    datacontentLen += 14;
                    datacontentLen += 1 + savePath.length() + binFileName.length();
                    datacontentLen += tempBuf.length;
                } else {
                    datacontentLen += 14;
                    datacontentLen += tempBuf.length;
                }
                String dflag = BytesHelp.byte2HexStr(BytesHelp.int2Bytes(datacontentLen, 2));
                dflag = "8" + dflag.substring(1, dflag.length());
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes(dflag)); //报文下行标识及长度
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("02"));//报文起始符
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("0001"));//流水号
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.getFBTm());//发报时间
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.int2Bytes(index, 2));
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.int2Bytes(total, 2));
                datacontentLen = 0;
                if (index == 1) {
                    datacontentLen += 1 + savePath.length() + binFileName.length();
                    datacontentLen += tempBuf.length;
                } else {
                    datacontentLen += tempBuf.length;
                }
                respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.int2Bytes(datacontentLen, 2));
                if (index == 1) {
                    byte[] filenamebuff = BytesHelp.arrayApend(savePath.getBytes(), binFileName.getBytes());
                    respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.int2Bytes(filenamebuff.length, 1));
                    respPacket = BytesHelp.arrayApend(respPacket, filenamebuff);
                }
                respPacket = BytesHelp.arrayApend(respPacket, tempBuf);
                if (index == 1) {
                    respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("05"));//RTU2014年报文正文结束符
                } else if (index + 1 == total) {
                    respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("03"));//RTU2014年报文正文结束符
                } else {
                    respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("17"));//RTU2014年报文正文结束符
                }
                byte[] crc16 = BytesHelp.crcFun2014(respPacket);
                respPacket = BytesHelp.arrayApend(respPacket, crc16);//CRC16
                CommandEntity entity = new CommandEntity();
                entity.setDatagram(BytesHelp.byte2HexStr(respPacket));
                entity.setRtuCode(rtucode);
                entity.setNeedTry(true);
                entity.setTryCount(0);
                entity.setCreateTime(now);
                entity.setLiveTime(24 * 60);
                entity.setTry(false);
                entity.setWaittingBack(true);
                entity.setFuncCode("F1");
                entity.setBatchId(batchId);
                entity.setKey(Integer.toString(index));
                DataProcess.SubmitFileCommand(entity);
                index += 1;
                count += len;
            }

            RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
            HashOperations<String, String, String> ops = redisTemplate.opsForHash();
            JSONObject downFileBody = new JSONObject();
            downFileBody.put("fileName", binFileName);
            downFileBody.put("fileBlockSize", total);
            ops.put(rtucode, "toRtuFileInfo", downFileBody.toJSONString());

            //配置文件报文
            byte[] binFileCrc16 = BytesHelp.crcFun2014(databuff);
            String configStr = "LEVEL:2";
            byte[] configHc = new byte[]{0x0d, 0x0a};
            byte[] configBytes = configStr.getBytes();
            configBytes = BytesHelp.arrayApend(configBytes, configHc);
            int c1 = binFileCrc16[0] < 0 ? binFileCrc16[0] + 256 : binFileCrc16[0];
            int c2 = binFileCrc16[1] < 0 ? binFileCrc16[1] + 256 : binFileCrc16[1];
            configStr = "CRC16:" + String.format("%03d", c1) + "," + String.format("%03d", c2);
            configBytes = BytesHelp.arrayApend(configBytes, configStr.getBytes());
            configBytes = BytesHelp.arrayApend(configBytes, configHc);
            configStr = "CNT:0";
            configBytes = BytesHelp.arrayApend(configBytes, configStr.getBytes());
            configBytes = BytesHelp.arrayApend(configBytes, configHc);
            configStr = "RES:1";
            configBytes = BytesHelp.arrayApend(configBytes, configStr.getBytes());
            configBytes = BytesHelp.arrayApend(configBytes, configHc);
            configStr = "VER:" + binFileName;
            configBytes = BytesHelp.arrayApend(configBytes, configStr.getBytes());
            configBytes = BytesHelp.arrayApend(configBytes, configHc);
            String configpath = savePath + "config.txt";
            byte[] configPacket = BytesHelp.hexStr2Bytes("7E7E");  //帧起始符
            configPacket = BytesHelp.arrayApend(configPacket, BytesHelp.hexStr2Bytes(rtucode));//遥测站地址
            configPacket = BytesHelp.arrayApend(configPacket, BytesHelp.hexStr2Bytes("01"));//中心站地址
            configPacket = BytesHelp.arrayApend(configPacket, BytesHelp.hexStr2Bytes("0000"));//密码
            configPacket = BytesHelp.arrayApend(configPacket, BytesHelp.hexStr2Bytes("F4"));//功能码
            int datacontentLen = 0;
            datacontentLen += 14;
            datacontentLen += 1 + configpath.length();
            datacontentLen += configBytes.length;
            String dflag = BytesHelp.byte2HexStr(BytesHelp.int2Bytes(datacontentLen, 2));
            dflag = "8" + dflag.substring(1, dflag.length());
            configPacket = BytesHelp.arrayApend(configPacket, BytesHelp.hexStr2Bytes(dflag)); //报文下行标识及长度
            configPacket = BytesHelp.arrayApend(configPacket, BytesHelp.hexStr2Bytes("02"));//报文起始符
            configPacket = BytesHelp.arrayApend(configPacket, BytesHelp.hexStr2Bytes("0001"));//流水号
            configPacket = BytesHelp.arrayApend(configPacket, BytesHelp.getFBTm());//发报时间
            configPacket = BytesHelp.arrayApend(configPacket, BytesHelp.int2Bytes(1, 2));
            configPacket = BytesHelp.arrayApend(configPacket, BytesHelp.int2Bytes(1, 2));
            datacontentLen = 0;
            datacontentLen += 1 + configpath.length();
            datacontentLen += configBytes.length;
            configPacket = BytesHelp.arrayApend(configPacket, BytesHelp.int2Bytes(datacontentLen, 2));
            byte[] configfilenamebuff = configpath.getBytes();
            configPacket = BytesHelp.arrayApend(configPacket, BytesHelp.int2Bytes(configfilenamebuff.length, 1));
            configPacket = BytesHelp.arrayApend(configPacket, configfilenamebuff);
            configPacket = BytesHelp.arrayApend(configPacket, configBytes);
            configPacket = BytesHelp.arrayApend(configPacket, BytesHelp.hexStr2Bytes("05"));//RTU2014年报文正文结束符
            byte[] crc16 = BytesHelp.crcFun2014(configPacket);
            configPacket = BytesHelp.arrayApend(configPacket, crc16);//CRC16
            CommandEntity configentity = new CommandEntity();
            configentity.setDatagram(BytesHelp.byte2HexStr(configPacket));
            configentity.setRtuCode(rtucode);
            configentity.setNeedTry(true);
            configentity.setTryCount(0);
            configentity.setCreateTime(now);
            configentity.setLiveTime(24 * 60);
            configentity.setTry(false);
            configentity.setWaittingBack(true);
            configentity.setFuncCode("F4");
            configentity.setBatchId(batchId);
            configentity.setKey(Integer.toString(1));
            DataProcess.SubmitFileCommand(configentity);

            //RTU重启指令
            byte[] respPacket = BytesHelp.hexStr2Bytes("7E7E");  //帧起始符
            respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes(rtucode));//遥测站地址
            respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("91"));//中心站地址
            respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("0000"));//密码
            respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("F3"));//功能码
            respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("8008")); //报文下行标识及长度
            respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("02"));//报文起始符
            respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("0001"));//流水号
            respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.getFBTm());//发报时间
            respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("05"));//RTU2014年报文正文结束符
            crc16 = BytesHelp.crcFun2014(respPacket);
            respPacket = BytesHelp.arrayApend(respPacket, crc16);//CRC16
            CommandEntity entity = new CommandEntity();
            entity.setDatagram(BytesHelp.byte2HexStr(respPacket));
            entity.setRtuCode(rtucode);
            entity.setNeedTry(false);
            entity.setTryCount(0);
            entity.setCreateTime(new Date());
            entity.setLiveTime(24 * 60);
            entity.setWaittingBack(true);
            entity.setTry(false);
            entity.setFuncCode("F3");
            entity.setBatchId(batchId);
            DataProcess.SubmitFileCommand(entity);
            return true;
        } catch (Exception e) {
            LogHelper.error(e);
        }
        return false;
    }

    /**
     * RTU升级，所有RTU都升级到此版本
     *
     * @param jsonData
     * @return
     */
//    @PostMapping(value = "DataCollectServer/Manage/BinFile")
//    public JSONObject submitFile(@RequestBody JSONObject jsonData) {
//        JSONObject result = new JSONObject();
//        try {
//            String datagram = jsonData.getString("datagram");
//            String fileName = jsonData.getString("fileName");
//            String funcCode = jsonData.getString("funcCode");
//            Date now = new Date();
//            CommandEntity entity = new CommandEntity();
//            entity.setDatagram(datagram);
//            entity.setNeedTry(true);
//            entity.setTryCount(0);
//            entity.setCreateTime(now);
//            entity.setLiveTime(24 * 60);
//            entity.setFileName(fileName);
//            entity.setFuncCode(funcCode);
//            entity.setTry(false);
//            if (DataProcessHolder.newInstance().dataProcess.relpayFileToAll.offer(entity)) {
//                result.put("code", "0");
//            } else {
//                result.put("code", "1");
//                result.put("msg", "无法写入队列");
//            }
//        } catch (Exception e) {
//            LogHelper.error(e);
//            result.put("code", "1");
//        }
//        return result;
//    }
}
