ShzzDevicePullService.java 27.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
package com.iot.scheduler.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.iot.scheduler.model.DeviceToken;
import com.iot.scheduler.model.QxDeviceInfo;
import com.iot.scheduler.model.QxDeviceInfoDetail;
import com.iot.scheduler.utils.SqlTypedValueUtils;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.*;
import java.util.Date;

/**
 * 盛华纸业应用数据同步
 */
@Slf4j
@Service
public class ShzzDevicePullService {

    @Value("${shzz.iot.organizeId:}")
    private String iotOrganizeId;
    @Value("${shzz.iot.profileId}")
    private String iotProfileId;
    @Value("${shzz.iot.deviceProfileId}")
    private String iotDeviceProfileId;
    @Value("${shzz.iot.userName:}")
    private String iotUserName;
    @Value("${shzz.iot.password:}")
    private String iotPassword;
    @Value("${shzz.iot.tokenUrl}")
    private String iotTokenUrl;
    @Value("${shzz.iot.infoUrl}")
    private String iotDeviceInfoUrl;
    @Value("${shzz.iot.detailUrl}")
    private String iotDeviceDetailUrl;

    @Value("${hn.third.jdbcUrl:jdbc:postgresql://106.15.73.210:5433/thingskit}")
    private String jdbcUrl;

    @Value("${hn.third.jdbcUserName:postgres}")
    private String jdbcUserName;

    @Value("${hn.third.jdbcPassword:postgres}")
    private String jdbcPassword;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    public void pullDeviceAndPushToIot() {
        JSONArray deviceInfoList = getDeviceInfo();
        JSONArray deviceInfoList2 = getDeviceInfo2();
        deviceInfoList.addAll(deviceInfoList2);
        List<QxDeviceInfo> qxDeviceInfos = new ArrayList<>();
        List<QxDeviceInfoDetail> qxAddDeviceInfoDetails = new ArrayList<>();
        Map<String, QxDeviceInfoDetail> qxDeviceInfoDetailMap = new HashMap<>();
        for (Object o : deviceInfoList) {
            JSONObject deviceInfoJson = (JSONObject) o;
            QxDeviceInfo qxDeviceInfo = new QxDeviceInfo();
            qxDeviceInfo.setDeviceType("SENSOR");
            qxDeviceInfo.setTransportType("DEFAULT");
            qxDeviceInfo.setOrganizationId(iotOrganizeId);
            qxDeviceInfo.setDeviceProfileId(iotDeviceProfileId);
            qxDeviceInfo.setProfileId(iotProfileId);
//            //项目状态(1:在线,2:离线,3:报警)
//            Integer projectState = deviceInfoJson.getInteger("projectState");
//            if (projectState != null) {
//                qxDeviceInfo.setDescription(String.valueOf(projectState));
//            }

            //项目类型
            qxDeviceInfo.setLabel("生产设备");
            //设备名称
            String deviceName = deviceInfoJson.getString("deviceName");

            qxDeviceInfo.setName(deviceName);
            qxDeviceInfo.setBrand(deviceName);
            //序列号
            String dtuSn = deviceInfoJson.getString("dtuSn");
            qxDeviceInfo.setSn(dtuSn);
            DeviceToken deviceToken = new DeviceToken();
            deviceToken.setCredentialsType("ACCESS_TOKEN");
            deviceToken.setCredentialsId(dtuSn);
            deviceToken.setCredentialsValue(dtuSn);
            qxDeviceInfo.setDeviceToken(deviceToken);
            qxDeviceInfos.add(qxDeviceInfo);
            QxDeviceInfoDetail qxDeviceInfoDetail = new QxDeviceInfoDetail();
            qxDeviceInfoDetail.setAlarm(false);
            //灯状态(0:灭灯,1:红,2:黄,3:绿,4:蓝)
            Integer lampState = deviceInfoJson.getInteger("lampState");
            switch (lampState) {
                case 0:
                    qxDeviceInfoDetail.setStatus("OFF");
                    break;
                case 1:
                    qxDeviceInfoDetail.setStatus("ERROR");
                    qxDeviceInfoDetail.setAlarm(true);
                    String totalCapacity = getTotalCapacity("gh_total_capacity_" + dtuSn, 0D);
                    qxDeviceInfoDetail.setCumulativeOutput(Double.valueOf(totalCapacity));
                    break;
                case 2:
                    qxDeviceInfoDetail.setStatus("STAND");
                    totalCapacity = getTotalCapacity("gh_total_capacity_" + dtuSn, 0D);
                    qxDeviceInfoDetail.setCumulativeOutput(Double.valueOf(totalCapacity));
                    break;
                case 3:
                    qxDeviceInfoDetail.setStatus("RUN");
                    //先从缓存里面拿token信息
                    totalCapacity = getTotalCapacity("gh_total_capacity_" + dtuSn, deviceInfoJson.getDouble("production"));
                    qxDeviceInfoDetail.setCumulativeOutput(Double.valueOf(totalCapacity));
                    qxDeviceInfoDetail.setCapacity(deviceInfoJson.getDouble("production"));
                    break;
                default:
                    continue;
            }

            if (lampState == 0) {
                continue;
            }

            qxDeviceInfoDetail.setStartTime(new Date());
            qxDeviceInfoDetail.setDtuSn(dtuSn);
            qxDeviceInfoDetailMap.put(dtuSn, qxDeviceInfoDetail);
            qxAddDeviceInfoDetails.add(qxDeviceInfoDetail);
        }

        //将数据同步到IOT平台
        Map<String, String> qxParam = new HashMap<>(2);
        qxParam.put("username", iotUserName);
        qxParam.put("password", iotPassword);

        HttpPost qxHttpPost = new HttpPost(iotTokenUrl);
        String qxResult = sendPost(qxHttpPost, JSON.toJSONString(qxParam));
        if (StringUtils.isBlank(qxResult)) {
            return;
        }
        Map<String, Object> qxRes = JSON.parseObject(qxResult, new TypeReference<>() {
        });

        String qxAccessToken = (String) qxRes.get("token");
        if (StringUtils.isBlank(qxAccessToken)) {
            return;
        }

        BasicHeader qxAuthorization = new BasicHeader("X-Authorization", "Bearer " + qxAccessToken);
        if (!CollectionUtils.isEmpty(qxDeviceInfos)) {
            HttpPost qxDeviceInfoPost = new HttpPost(iotDeviceInfoUrl);
            qxDeviceInfoPost.addHeader(qxAuthorization);
            for (QxDeviceInfo qxDeviceInfo : qxDeviceInfos) {
                // todo
                String syncDeviceInfo = sendPost(qxDeviceInfoPost, JSON.toJSONString(qxDeviceInfo));
                //log.info("同步设备信息 syncDeviceInfo:{}", syncDeviceInfo);
            }
        }

        if (!CollectionUtils.isEmpty(qxAddDeviceInfoDetails)) {
            for (QxDeviceInfoDetail qxDeviceInfoDetail : qxAddDeviceInfoDetails) {
                String qxDeviceInfoDetailUrlStr = iotDeviceDetailUrl + qxDeviceInfoDetail.getDtuSn() + "/telemetry";
                HttpPost qxDeviceInfoDetailPost = new HttpPost(qxDeviceInfoDetailUrlStr);
                qxDeviceInfoDetailPost.addHeader(qxAuthorization);
                String syncDeviceInfoDetail = sendPost(qxDeviceInfoDetailPost, JSON.toJSONString(qxDeviceInfoDetail));
            }
        }
    }

    private JSONArray getDeviceInfo2() {
        Connection connection = null;
        PreparedStatement statement = null;
        PreparedStatement tsKvStatement = null;
        ResultSet resultSet = null;
        ResultSet tsKvResultSet = null;
        HikariDataSource dataSource = null;
        List<Object> resultList = new ArrayList<>();

        log.info("开始连接数据库2,URL: {}", jdbcUrl);

        try {
            HikariConfig config = new HikariConfig();
            config.setJdbcUrl(jdbcUrl);
            config.setUsername(jdbcUserName);
            config.setPassword(jdbcPassword);
            config.setDriverClassName("org.postgresql.Driver");
            config.setMaximumPoolSize(5);
            config.setMinimumIdle(5);
            config.setConnectionTimeout(60000);
            config.setConnectionTestQuery("SELECT 1");

            dataSource = new HikariDataSource(config);
            log.info("Hikari连接池配置完成2");

            connection = dataSource.getConnection();
            log.info("数据库连接成功2");

            String selectSql = "SELECT\n" +
                    "de.id,\n" +
                    "de.name,\n" +
                    "dc.credentials_id,\n" +
                    "CASE\n" +
                    "    WHEN ak2.long_v IS NULL OR (ak.bool_v = FALSE AND ak2.long_v IS NOT NULL) THEN 'OFF'\n" +
                    "    WHEN tkl.long_v = 1 THEN 'ERROR'\n" +
                    "    ELSE 'RUN'\n" +
                    "  END AS status \n" +
                    "FROM device de \n" +
                    "LEFT JOIN ts_kv_latest tkl on de.id = tkl.entity_id AND tkl.key = '528'\n" +
                    "LEFT JOIN attribute_kv ak ON de.id = ak.entity_id AND ak.entity_type = 'DEVICE' AND ak.attribute_key = 'active'\n" +
                    "LEFT JOIN attribute_kv ak2 ON de.id = ak2.entity_id AND ak2.entity_type = 'DEVICE' AND ak2.attribute_key = 'lastActivityTime'\n" +
                    "LEFT JOIN device_credentials dc ON de.id = dc.device_id\n" +
                    "WHERE de.organization_id = '3304ebd5-71ae-448a-91a2-e3b4d6ae258a'\n" +
                    "AND de.device_profile_id = '63042200-02fe-11f1-9cb8-e3376d1e7978'\n";

            statement = connection.prepareStatement(selectSql);
            log.info("执行SQL查询2: {}", selectSql);

            resultSet = statement.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            log.info("查询结果集元数据获取成功2,共{}列", columnCount);

            int rowCount = 0;
            while (resultSet.next()) {
                List<Object> result = new ArrayList<>(columnCount);
                for (int index = 1; index <= columnCount; index++) {
                    int columnType = metaData.getColumnType(index);
                    Object value = SqlTypedValueUtils.getTypedValue(resultSet, index, columnType);
                    result.add(value);
                }

                // 处理状态为RUN的设备,进行二次验证
                if (result.size() >= 4 && "RUN".equals(result.get(3))) {
                    String deviceId = result.get(0).toString();
                    String deviceName = result.get(1).toString();

                    // 查询该设备最近两条key='531'的数据
                    String tsKvSql = "SELECT str_v FROM ts_kv " +
                            "WHERE entity_id = ? AND key = '531' " +
                            "ORDER BY ts DESC LIMIT 2";

                    tsKvStatement = connection.prepareStatement(tsKvSql);
                    tsKvStatement.setString(1, deviceId);
                    tsKvResultSet = tsKvStatement.executeQuery();

                    List<String> strVValues = new ArrayList<>(2);
                    while (tsKvResultSet.next()) {
                        strVValues.add(tsKvResultSet.getString("long_v"));
                    }

                    // 如果查询到两条数据且值不同,才认为是真正的RUN状态
                    // 否则改为STAND状态
                    if (strVValues.size() < 2 ||
                            (strVValues.size() == 2 && strVValues.get(0).equals(strVValues.get(1)))) {
                        result.set(3, "STAND");
                        log.debug("设备{}状态由RUN修正为STAND,long_v值: {}", deviceName, strVValues);
                    } else {
                        log.debug("设备{}确认为RUN状态,最近两个long_v值不同: {} 和 {}",
                                deviceName, strVValues.get(0), strVValues.get(1));
                    }

                    // 关闭ts_kv查询的相关资源
                    if (tsKvResultSet != null) {
                        tsKvResultSet.close();
                        tsKvResultSet = null;
                    }
                    if (tsKvStatement != null) {
                        tsKvStatement.close();
                        tsKvStatement = null;
                    }
                }

                resultList.add(result);
                rowCount++;

                // 每处理100行记录一次日志
                if (rowCount % 100 == 0) {
                    log.info("已处理{}行数据", rowCount);
                }
            }

            log.info("数据查询完成,共获取{}行数据", rowCount);

        } catch (SQLException e) {
            log.error("数据库操作异常,URL: {}, 用户名: {}", jdbcUrl, jdbcUserName, e);
        } catch (Exception e) {
            log.error("初始化数据库连接或查询数据时发生异常", e);
        } finally {
            // 释放资源
            try {
                if (tsKvResultSet != null) tsKvResultSet.close();
                if (tsKvStatement != null) tsKvStatement.close();
                if (resultSet != null) resultSet.close();
                if (statement != null) statement.close();
                if (connection != null) connection.close();
                log.info("数据库连接资源已释放");
            } catch (SQLException e) {
                log.error("关闭数据库资源时发生异常", e);
            }

            if (dataSource != null) {
                try {
                    dataSource.close();
                    log.info("HikariDataSource连接池已关闭");
                } catch (Exception e) {
                    log.error("关闭HikariDataSource连接池时发生异常", e);
                }
            }
        }

        log.info("数据库操作完成,返回{}条记录", resultList.size());
        List<String> deviceNameList = Arrays.asList(
                "新发现KSJ-160智能纸杯机7oz-1", "新发现KSJ-160智能纸杯机7oz-2", "新发现KSJ-160智能纸杯机6.5oz", "新发现KSJ-160智能纸杯机8oz-1",
                "新发现KSJ-160智能纸杯机8oz-2", "新发现PJJ-III型纸容器品检机6.5oz/7oz", "新发现PJJ-III型纸容器品检机7.5oz/8oz",
                "新发现PJJ-I-02型纸容器品检机7.5oz/8oz", "新发现PJJ-I-02型纸容器品检机7.5oz/12oz", "新发现KSJ-160智能快速纸杯机7.5oz-1",
                "新发现KSJ-160智能快速纸杯机7.5oz-2", "新发现KSJ-160智能快速纸杯机12oz", "智能中速纸杯机JBZ-22D-1",
                "智能中速纸杯机JBZ-22D-2", "智能中速纸杯机JBZ-22D-3", "智能中速纸杯机JBZ-22D-4", "智能中速纸杯机JBZ-22D-5", "智能中速纸杯机JBZ-22D-6",
                "智能中速纸杯机JBZ-22D-7", "智能中速纸杯机JBZ-22D-8", "智能中速纸杯机JBZ-22D-9", "智能中速纸杯机JBZ-22S-1", "智能中速纸杯机JBZ-22S-2",
                "高速智能纸杯机DEBAO-100S", "纸机杯XC-L12齿轮340-B型-1", "纸机杯XC-L12齿轮340-B型-2", "中速外贴机SM100-KT490(12oz)",
                "中速外贴机SM100-KT491(4oz)", "中速外贴机SM100-KY373", "中速外贴机SM100-KT489(16oz)", "外贴机8oz", "外贴机12oz", "模切机1",
                "模切机2", "模切机3", "模切机4", "模切机5");

        JSONArray jsonArray = new JSONArray();
        List<JSONObject> jsonObjectList = new ArrayList<>(resultList.size());
        for (Object result : resultList) {
            List<Object> dataList = (ArrayList) result;
            int index = deviceNameList.indexOf(dataList.get(1)); // 注意:现在name在索引1位置

            Map<String, Object> map = new HashMap<>(3);
            map.put("deviceName", dataList.get(1));
            map.put("dtuSn", dataList.get(2));

            String status = dataList.get(3).toString();
            if ("OFF".equals(status)) {
                map.put("lampState", 0);
            } else if ("ERROR".equals(status)) {
                map.put("lampState", 1);
            } else if ("STAND".equals(status)) {
                map.put("lampState", 2);
            } else if ("RUN".equals(status)) {
                map.put("lampState", 3);
            }

            if (index < 11) {
                map.put("production", 130D);
            } else if (index == 11) {
                map.put("production", 120D);
            } else if (index < 23) {
                map.put("production", 80D);
            } else if (index == 23) {
                map.put("production", 110D);
            } else if (index < 26) {
                map.put("production", 50D);
            } else if (index < 30) {
                map.put("production", 120D);
            } else {
                map.put("production", 80D);
            }

            JSONObject jsonObject = new JSONObject();
            jsonObject.putAll(map);
            jsonObjectList.add(jsonObject);
        }

        jsonArray.addAll(jsonObjectList);
        return jsonArray;
    }

    private JSONArray getDeviceInfo() {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        HikariDataSource dataSource = null;
        List<Object> resultList = new ArrayList<>();

        log.info("开始连接数据库,URL: {}", jdbcUrl);

        try {
            HikariConfig config = new HikariConfig();
            config.setJdbcUrl(jdbcUrl);
            config.setUsername(jdbcUserName);
            config.setPassword(jdbcPassword);
            config.setDriverClassName("org.postgresql.Driver");
            config.setMaximumPoolSize(5);
            config.setMinimumIdle(5);
            config.setConnectionTimeout(60000);
            config.setConnectionTestQuery("SELECT 1");

            dataSource = new HikariDataSource(config);
            log.info("Hikari连接池配置完成");

            connection = dataSource.getConnection();
            log.info("数据库连接成功");

            String selectSql = "SELECT\n" +
                    "de.name,\n" +
                    "dc.credentials_id,\n" +
                    "CASE\n" +
                    "    WHEN ak2.long_v IS NULL OR (ak.bool_v = FALSE AND ak2.long_v IS NOT NULL) THEN 'OFF'\n" +
                    "    WHEN tkl.long_v = 1 THEN 'ERROR'\n" +
                    "    WHEN tkl2.long_v = 1 THEN 'STAND'\n" +
                    "    WHEN tkl3.long_v = 1 THEN 'RUN'\n" +
                    "    ELSE 'OFF'\n" +
                    "  END AS status \n" +
                    "FROM device de \n" +
                    "LEFT JOIN ts_kv_latest tkl on de.id = tkl.entity_id AND tkl.key = '64'\n" +
                    "LEFT JOIN ts_kv_latest tkl2 on de.id = tkl2.entity_id AND tkl2.key = '535'\n" +
                    "LEFT JOIN ts_kv_latest tkl3 on de.id = tkl3.entity_id AND tkl3.key = '534'\n" +
                    "LEFT JOIN attribute_kv ak ON de.id = ak.entity_id AND ak.entity_type = 'DEVICE' AND ak.attribute_key = 'active'\n" +
                    "LEFT JOIN attribute_kv ak2 ON de.id = ak2.entity_id AND ak2.entity_type = 'DEVICE' AND ak2.attribute_key = 'lastActivityTime'\n" +
                    "LEFT JOIN device_credentials dc ON de.id = dc.device_id\n" +
                    "WHERE de.organization_id = '3304ebd5-71ae-448a-91a2-e3b4d6ae258a'\n" +
                    "AND de.device_profile_id = '1f2183a0-0562-11f1-9cb8-e3376d1e7978'\n";

            statement = connection.prepareStatement(selectSql);
            log.info("执行SQL查询: {}", selectSql);

            resultSet = statement.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            log.info("查询结果集元数据获取成功,共{}列", columnCount);

            int rowCount = 0;
            while (resultSet.next()) {
                List<Object> result = new ArrayList<>(columnCount);
                for (int index = 1; index <= columnCount; index++) {
                    int columnType = metaData.getColumnType(index);
                    Object value = SqlTypedValueUtils.getTypedValue(resultSet, index, columnType);
                    result.add(value);
                }
                resultList.add(result);
                rowCount++;

                // 每处理1000行记录一次日志
                if (rowCount % 1000 == 0) {
                    log.info("已处理{}行数据", rowCount);
                }
            }

            log.info("数据查询完成,共获取{}行数据", rowCount);

        } catch (SQLException e) {
            log.error("数据库操作异常,URL: {}, 用户名: {}", jdbcUrl, jdbcUserName, e);
        } catch (Exception e) {
            log.error("初始化数据库连接或查询数据时发生异常", e);
        } finally {
            // 释放资源
            try {
                if (resultSet != null) resultSet.close();
                if (statement != null) statement.close();
                if (connection != null) connection.close();
                log.info("数据库连接资源已释放");
            } catch (SQLException e) {
                log.error("关闭数据库资源时发生异常", e);
            }

            if (dataSource != null) {
                try {
                    dataSource.close();
                    log.info("HikariDataSource连接池已关闭");
                } catch (Exception e) {
                    log.error("关闭HikariDataSource连接池时发生异常", e);
                }
            }
        }

        log.info("数据库操作完成,返回{}条记录", resultList.size());
        List<String> deviceNameList = Arrays.asList(
                "新发现KSJ-160智能纸杯机7oz-1", "新发现KSJ-160智能纸杯机7oz-2", "新发现KSJ-160智能纸杯机6.5oz", "新发现KSJ-160智能纸杯机8oz-1",
                "新发现KSJ-160智能纸杯机8oz-2", "新发现PJJ-III型纸容器品检机6.5oz/7oz", "新发现PJJ-III型纸容器品检机7.5oz/8oz",
                "新发现PJJ-I-02型纸容器品检机7.5oz/8oz", "新发现PJJ-I-02型纸容器品检机7.5oz/12oz", "新发现KSJ-160智能快速纸杯机7.5oz-1",
                "新发现KSJ-160智能快速纸杯机7.5oz-2", "新发现KSJ-160智能快速纸杯机12oz", "智能中速纸杯机JBZ-22D-1",
                "智能中速纸杯机JBZ-22D-2", "智能中速纸杯机JBZ-22D-3", "智能中速纸杯机JBZ-22D-4", "智能中速纸杯机JBZ-22D-5", "智能中速纸杯机JBZ-22D-6",
                "智能中速纸杯机JBZ-22D-7", "智能中速纸杯机JBZ-22D-8", "智能中速纸杯机JBZ-22D-9", "智能中速纸杯机JBZ-22S-1", "智能中速纸杯机JBZ-22S-2",
                "高速智能纸杯机DEBAO-100S", "纸机杯XC-L12齿轮340-B型-1", "纸机杯XC-L12齿轮340-B型-2", "中速外贴机SM100-KT490(12oz)",
                "中速外贴机SM100-KT491(4oz)", "中速外贴机SM100-KY373", "中速外贴机SM100-KT489(16oz)", "外贴机8oz", "外贴机12oz", "模切机1",
                "模切机2", "模切机3", "模切机4", "模切机5");

        JSONArray jsonArray = new JSONArray();
        List<JSONObject> jsonObjectList = new ArrayList<>(resultList.size());
        for (Object result : resultList) {
            List<Object> dataList = (ArrayList) result;
            int index = deviceNameList.indexOf(dataList.get(0));
            Map<String, Object> map = new HashMap<>(3);
            map.put("deviceName", dataList.get(0));
            map.put("dtuSn", dataList.get(1));
            String status = dataList.get(2).toString();
            if ("OFF".equals(status)) {
                map.put("lampState", 0);
            } else if ("ERROR".equals(status)) {
                map.put("lampState", 1);
            } else if ("STAND".equals(status)) {
                map.put("lampState", 2);
            } else if ("RUN".equals(status)) {
                map.put("lampState", 3);
            }

            if (index < 11) {
                map.put("production", 130D);
            } else if (index == 11) {
                map.put("production", 120D);
            } else if (index < 23) {
                map.put("production", 80D);
            } else if (index == 23) {
                map.put("production", 110D);
            } else if (index < 26) {
                map.put("production", 50D);
            } else if (index < 30) {
                map.put("production", 120D);
            } else {
                map.put("production", 80D);
            }

            JSONObject jsonObject = new JSONObject();
            jsonObject.putAll(map);
            jsonObjectList.add(jsonObject);
        }

        jsonArray.addAll(jsonObjectList);
        return jsonArray;


//        JSONArray jsonArray = new JSONArray();
//        List<JSONObject> jsonObjectList = new ArrayList<>(38);
//        LocalTime currentTime = LocalTime.now();
//        LocalTime startTime = LocalTime.of(8, 0, 0);  // 08:00:00
//        LocalTime endTime = LocalTime.of(18, 0, 0);   // 18:00:00
//        boolean isWithinRange =
//                !currentTime.isBefore(startTime) &&
//                        currentTime.isBefore(endTime);
//        for (int index = 0; index < deviceNameList.size(); index++) {
//            Map<String, Object> map = new HashMap<>(3);
//            map.put("deviceName", deviceNameList.get(index));
//            map.put("dtuSn", "SGH20250123" + String.format("%03d", index));
//            map.put("lampState", isWithinRange ? 3 : 0);
//            if (index < 11) {
//                map.put("production", 130D);
//            } else if (index == 11) {
//                map.put("production", 120D);
//            } else if (index < 23) {
//                map.put("production", 80D);
//            } else if (index == 23) {
//                map.put("production", 110D);
//            } else if (index < 26) {
//                map.put("production", 50D);
//            } else if (index < 30) {
//                map.put("production", 120D);
//            } else {
//                map.put("production", 80D);
//            }
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.putAll(map);
//            jsonObjectList.add(jsonObject);
//        }
//
//        jsonArray.addAll(jsonObjectList);
//        return jsonArray;
    }

    private String getTotalCapacity(String key, Double production) {
        String totalCapacity = redisTemplate.opsForValue().get(key);
        Double totalCapacityD = 0D;
        if (StringUtils.isEmpty(totalCapacity)) {
            totalCapacityD = production;
        } else {
            totalCapacityD = Double.parseDouble(totalCapacity) + production;
        }

        redisTemplate.opsForValue().set(key, String.valueOf(totalCapacityD));
        return String.valueOf(totalCapacityD);
    }

    private String sendPost(HttpPost httpPost, String jsonData) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        StringEntity entity = new StringEntity(jsonData, ContentType.create("application/json", Consts.UTF_8));
        httpPost.setEntity(entity);
        String result = null;
        try {
            CloseableHttpResponse execute = httpClient.execute(httpPost);
            HttpEntity res = execute.getEntity();
            InputStream is = res.getContent();
            int len;
            byte[] buf = new byte[128];
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            while ((len = is.read(buf)) != -1) {
                byteArrayOutputStream.write(buf, 0, len);
            }
            result = byteArrayOutputStream.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}