jiangping
2023-10-09 5e66e66dc2561c86893d483cab57128ebbd9bc5b
集成mqtt
已添加9个文件
已修改7个文件
910 ■■■■■ 文件已修改
server/platform/src/main/java/com/doumee/api/business/LocksController.java 15 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
server/pom.xml 5 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
server/services/src/main/java/com/doumee/core/annotation/excel/ExcelColumn.java 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
server/services/src/main/java/com/doumee/core/annotation/excel/ExcelDataHandlerAdapter.java 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
server/services/src/main/java/com/doumee/core/annotation/excel/ExcelExporter.java 507 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
server/services/src/main/java/com/doumee/core/annotation/excel/ExportExcelUtils.java 88 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
server/services/src/main/java/com/doumee/core/constants/Constants.java 8 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
server/services/src/main/java/com/doumee/core/mqtt/config/MqttClientInit.java 51 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
server/services/src/main/java/com/doumee/core/mqtt/config/MqttConfig.java 34 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
server/services/src/main/java/com/doumee/core/mqtt/service/MqttPushCallback.java 33 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
server/services/src/main/java/com/doumee/core/mqtt/service/MqttToolService.java 55 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
server/services/src/main/java/com/doumee/service/business/DeviceService.java 20 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
server/services/src/main/java/com/doumee/service/business/DeviceSubcribeService.java 18 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
server/services/src/main/java/com/doumee/service/business/impl/DeviceServiceImpl.java 35 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
server/services/src/main/java/com/doumee/service/business/impl/DeviceSubscribeServiceImpl.java 25 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
server/services/src/main/resources/application-dev.yml 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
server/platform/src/main/java/com/doumee/api/business/LocksController.java
@@ -7,6 +7,7 @@
import com.doumee.core.model.PageData;
import com.doumee.core.model.PageWrap;
import com.doumee.dao.business.model.Locks;
import com.doumee.service.business.DeviceService;
import com.doumee.service.business.LocksService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@@ -29,6 +30,8 @@
    @Autowired
    private LocksService locksService;
    @Autowired
    private DeviceService deviceService;
    @PreventRepeat
    @ApiOperation("新建")
@@ -50,7 +53,7 @@
    @GetMapping("/delete/batch")
    @RequiresPermissions("business:locks:delete")
    public ApiResponse deleteByIdInBatch(@RequestParam String ids) {
        String [] idArray = ids.split(",");
        String[] idArray = ids.split(",");
        List<String> idList = new ArrayList<>();
        for (String id : idArray) {
            idList.add(id);
@@ -70,14 +73,14 @@
    @ApiOperation("分页查询")
    @PostMapping("/page")
    @RequiresPermissions("business:locks:query")
    public ApiResponse<PageData<Locks>> findPage (@RequestBody PageWrap<Locks> pageWrap) {
    public ApiResponse<PageData<Locks>> findPage(@RequestBody PageWrap<Locks> pageWrap) {
        return ApiResponse.success(locksService.findPage(pageWrap));
    }
    @ApiOperation("导出Excel")
    @PostMapping("/exportExcel")
    @RequiresPermissions("business:locks:exportExcel")
    public void exportExcel (@RequestBody PageWrap<Locks> pageWrap, HttpServletResponse response) {
    public void exportExcel(@RequestBody PageWrap<Locks> pageWrap, HttpServletResponse response) {
        ExcelExporter.build(Locks.class).export(locksService.findPage(pageWrap).getRecords(), "锁头信息表", response);
    }
@@ -87,4 +90,10 @@
    public ApiResponse findById(@PathVariable String id) {
        return ApiResponse.success(locksService.findById(id));
    }
    @ApiOperation("测试mqtt消息发送")
    @PostMapping("/testMqtt")
    public ApiResponse  testMqtt(@RequestBody  Locks locks) {
        return ApiResponse.success(deviceService.openLock(locks));
    }
}
server/pom.xml
@@ -285,6 +285,11 @@
      <artifactId>wechatpay-java</artifactId>
      <version>0.2.11</version>
    </dependency>
    <dependency>
      <groupId>org.eclipse.paho</groupId>
      <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
      <version>1.2.2</version>
    </dependency>
  </dependencies>
server/services/src/main/java/com/doumee/core/annotation/excel/ExcelColumn.java
@@ -8,7 +8,7 @@
/**
 * æ ‡è®°ä¸ºExcel列
 * @author Eva.Caesar Liu
 * @date 2022/03/15 09:54
 * @date 2022/04/18 18:12
 */
@Inherited
@Target(ElementType.FIELD)
@@ -19,6 +19,7 @@
     * åˆ—名
     */
    String name();
    /**
     * åˆ—宽(单位为字符),-1自动计算
@@ -33,7 +34,7 @@
    /**
     * å¯¹é½æ–¹å¼
     */
    HorizontalAlignment align() default HorizontalAlignment.LEFT;
    HorizontalAlignment  align() default HorizontalAlignment.LEFT;
    /**
     * åˆ—背景色
@@ -83,7 +84,7 @@
    /**
     * æ—¥æœŸæ ¼å¼
     */
    String dateFormat() default "yyyy-MM-dd HH:mm:ss";
    String dateFormat() default "yyyy-MM-dd";
    /**
     * è‡ªå®šä¹‰æ•°æ®å¤„理器
server/services/src/main/java/com/doumee/core/annotation/excel/ExcelDataHandlerAdapter.java
@@ -3,7 +3,7 @@
/**
 * Excel数据格式处理适配器
 * @author Eva.Caesar Liu
 * @date 2022/03/15 09:54
 * @date 2022/04/18 18:12
 */
public interface ExcelDataHandlerAdapter {
server/services/src/main/java/com/doumee/core/annotation/excel/ExcelExporter.java
@@ -4,24 +4,40 @@
import com.doumee.core.exception.BusinessException;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationConfigurationException;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
 * Excel导出实现
 * @author Eva.Caesar Liu
 * @date 2022/03/15 09:54
 * @date 2022/04/18 18:12
 */
@Data
public class ExcelExporter<T> {
@@ -31,6 +47,13 @@
    private Class<T> modelClass;
    private ExcelExporter(){}
    private final static Logger log = LoggerFactory.getLogger(ExcelExporter.class);
    private final static String EXCEL2003 = "xls";
    private final static String EXCEL2007 = "xlsx";
    /**
     * æž„造器
@@ -52,6 +75,8 @@
        SXSSFWorkbook sxssfWorkbook;
        try {
            sxssfWorkbook = new SXSSFWorkbook();
            CellStyle style = sxssfWorkbook.createCellStyle();
            Sheet sheet = sxssfWorkbook.createSheet(sheetName);
            // åˆ›å»ºåˆ—头
            sheet.createFreezePane(0, 1);
@@ -68,7 +93,7 @@
                    sheet.setColumnWidth(columnIndex, column.columnConfig.width() * 2 * 256);
                }
                // è®¾ç½®åˆ—头单元格
                configHeaderCell(sxssfWorkbook, cell, column.columnConfig);
                configHeaderCell(sxssfWorkbook, cell, column.columnConfig,style);
            }
            // åˆ›å»ºæ•°æ®è®°å½•
            for (int rowIndex = 0; rowIndex < data.size(); rowIndex++) {
@@ -78,7 +103,7 @@
                    Cell cell = row.createCell(columnIndex);
                    cell.setCellValue(getCellData(column, data.get(rowIndex)));
                    // è®¾ç½®æ•°æ®å•元格
                    configDataCell(sxssfWorkbook, cell, column.columnConfig);
                    configDataCell(sxssfWorkbook, cell, column.columnConfig,style);
                }
            }
            sxssfWorkbook.write(os);
@@ -125,7 +150,187 @@
    public void export (List<T> data, String fileName, HttpServletResponse response) {
        this.export(data, fileName, DEFAULT_SHEET_NAME, response);
    }
    /**
     * å¯¼å‡ºè‡³å“åº”流
     * @param data æ•°æ®
     * @param fileName Excel文件名
     * @param response HttpServletResponse对象
     */
    public void exportWithFirstAndEnd (List<T> data, String fileName,String first,String end, HttpServletResponse response) {
        this.exportWithFirstAndEnd(data, fileName, DEFAULT_SHEET_NAME, first,end,response);
    }
    /**
     * å¯¼å‡ºè‡³å“åº”流
     * @param data æ•°æ®
     * @param fileName Excel文件名
     * @param sheetName Sheet名称
     * @param response HttpServletResponse对象
     */
    public void exportWithFirstAndEnd (List<T> data, String fileName, String sheetName, String first,String end ,HttpServletResponse response) {
        try {
            String encodeFileName = URLEncoder.encode(fileName, Charset.forName("UTF-8").toString()) + ".xlsx";
            response.setHeader("Content-Disposition","attachment;filename=" + encodeFileName);
            response.setContentType("application/octet-stream");
            response.setHeader("eva-opera-type", "download");
            response.setHeader("eva-download-filename", encodeFileName);
            this.exportWithFirstAndEnd(data, sheetName,first,end, response.getOutputStream());
        } catch (IOException e) {
            throw new BusinessException(ResponseStatus.EXPORT_EXCEL_ERROR, e);
        }
    }
    /**
     * å¯¼å‡ºåˆ°æŒ‡å®šè¾“出流
     * @param data æ•°æ®
     * @param sheetName Sheet名称
     */
    public void exportWithFirstAndEnd (List<T> data, String sheetName,String first,String end, OutputStream os) {
        SXSSFWorkbook sxssfWorkbook;
        try {
            sxssfWorkbook = new SXSSFWorkbook();
            Sheet sheet = sxssfWorkbook.createSheet(sheetName);
            // åˆ›å»ºåˆ—头
            sheet.createFreezePane(0, 2);
            sheet.addMergedRegion(new CellRangeAddress(0   ,0,0,this.getColumns().size()-1));
            Row title = sheet.createRow(0);
            title.setHeight((short) 1000);
            Cell c = title.createCell(0);
            c.setCellValue(first);
            configFirstCell(sxssfWorkbook,c);
            Row header = sheet.createRow(1);
            header.setHeight((short)600);
            List<ColumnInfo> columns = this.getColumns();
            for (int columnIndex = 0; columnIndex < columns.size(); columnIndex++) {
                ColumnInfo column = columns.get(columnIndex);
                Cell cell = header.createCell(columnIndex);
                cell.setCellValue(new HSSFRichTextString(column.columnConfig.name()));
                // åˆ—宽设置
                if (column.columnConfig.width() == -1) {
                    sheet.setColumnWidth(columnIndex, column.columnConfig.name().length() * 2 * 256);
                } else {
                    sheet.setColumnWidth(columnIndex, column.columnConfig.width() * 2 * 256);
                }
                // è®¾ç½®åˆ—头单元格
                configHeaderCell(sxssfWorkbook, cell, column.columnConfig);
            }
            // åˆ›å»ºæ•°æ®è®°å½•
            for (int rowIndex = 0; rowIndex < data.size(); rowIndex++) {
                Row row = sheet.createRow(rowIndex + 2);
                for (int columnIndex = 0; columnIndex < columns.size(); columnIndex++) {
                    ColumnInfo column = columns.get(columnIndex);
                    Cell cell = row.createCell(columnIndex);
                    cell.setCellValue(getCellData(column, data.get(rowIndex)));
                    // è®¾ç½®æ•°æ®å•元格
                    configDataCell(sxssfWorkbook, cell, column.columnConfig);
                }
            }
            if(StringUtils.isNotBlank(end)){
                sheet.addMergedRegion(new CellRangeAddress(data.size()+2   ,data.size()+2,0,this.getColumns().size()-1));
                Row endRow = sheet.createRow(data.size()+2);
//            endRow.setHeight((short) 600);
                Cell c1 = endRow.createCell(0);
                c1.setCellValue(end);
                configEndCell(sxssfWorkbook,c1);
            }
            sxssfWorkbook.write(os);
            os.close();
        } catch (Exception e) {
            throw new BusinessException(ResponseStatus.EXPORT_EXCEL_ERROR, e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * é…ç½®æ•°æ®å•元格
     */
    private void configDataCell (SXSSFWorkbook workbook, Cell cell, ExcelColumn columnConfig) {
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(columnConfig.align());
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        // è®¾ç½®èƒŒæ™¯
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setFillForegroundColor(columnConfig.dataBackgroundColor().getIndex());
        // å­—体
        Font font = workbook.createFont();
        font.setFontHeightInPoints(columnConfig.fontSize());
        // å­—体颜色
        font.setColor(columnConfig.color().getIndex());
        // ç²—体
        font.setBold(columnConfig.bold());
        // æ–œä½“
        font.setItalic(columnConfig.italic());
        style.setFont(font);
        // è¾¹æ¡†
        configCellBorder(style);
        style.setWrapText(true);
        cell.setCellStyle(style);
    }
    /**
     * é…ç½®åˆ—头单元格
     */
    private void configFirstCell (SXSSFWorkbook workbook, Cell cell ) {
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        // è®¾ç½®èƒŒæ™¯
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
        // å­—体
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short)24);
        font.setBold(true);
        style.setFont(font);
        // è®¾ç½®è¾¹æ¡†
        configCellBorder(style);
        cell.setCellStyle(style);
    }
    /**
     * é…ç½®åˆ—头单元格
     */
    private void configEndCell (SXSSFWorkbook workbook, Cell cell ) {
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.RIGHT);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        // è®¾ç½®èƒŒæ™¯
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        // å­—体
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short)14);
        style.setFont(font);
        // è®¾ç½®è¾¹æ¡†
        configCellBorder(style);
        cell.setCellStyle(style);
    }
    /**
     * é…ç½®åˆ—头单元格
     */
    private void configHeaderCell (SXSSFWorkbook workbook, Cell cell, ExcelColumn columnConfig) {
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(columnConfig.align());
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        // è®¾ç½®èƒŒæ™¯
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//        style.setFillForegroundColor(columnConfig.backgroundColor().getIndex());
        style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
        // å­—体
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short)11);
        font.setColor(columnConfig.color().index);
        font.setBold(true);
        style.setFont(font);
        // è®¾ç½®è¾¹æ¡†
        style.setWrapText(true);
        configCellBorder(style);
        cell.setCellStyle(style);
    }
    /**
     * èŽ·å–åˆ—é›†åˆ
     */
@@ -147,11 +352,15 @@
        return new ArrayList<>(sortedFields.values());
    }
    public static void main(String[] args) {
        ExcelExporter m = new ExcelExporter();
//        ExcelExporter.build(UserSalaryListVO.class).getColumns();
    }
    /**
     * é…ç½®æ•°æ®å•元格
     */
    private void configDataCell (SXSSFWorkbook workbook, Cell cell, ExcelColumn columnConfig) {
        CellStyle style = workbook.createCellStyle();
    private void configDataCell (SXSSFWorkbook workbook, Cell cell, ExcelColumn columnConfig, CellStyle style) {
     //   CellStyle style = workbook.createCellStyle();
        style.setAlignment(columnConfig.align());
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        // è®¾ç½®èƒŒæ™¯
@@ -175,8 +384,8 @@
    /**
     * é…ç½®åˆ—头单元格
     */
    private void configHeaderCell (SXSSFWorkbook workbook, Cell cell, ExcelColumn columnConfig) {
        CellStyle style = workbook.createCellStyle();
    private void configHeaderCell (SXSSFWorkbook workbook, Cell cell, ExcelColumn columnConfig,CellStyle style) {
       // CellStyle style = workbook.createCellStyle();
        style.setAlignment(columnConfig.align());
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        // è®¾ç½®èƒŒæ™¯
@@ -263,4 +472,288 @@
        private Field field;
    }
    public static <T> List<T> readExcel(String path, Class<T> cls, MultipartFile file) {
        String fileName = file.getOriginalFilename();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            log.error("上传文件格式不正确");
        }
        List<T> dataList = new ArrayList<>();
        Workbook workbook = null;
        try {
            InputStream is = file.getInputStream();
            if (fileName.endsWith(EXCEL2007)) {
                workbook = new XSSFWorkbook(is);
            }
            if (fileName.endsWith(EXCEL2003)) {
                workbook = new HSSFWorkbook(is);
            }
            if (workbook != null) {
                //类映射  æ³¨è§£ value-->bean columns
                Map<String, List<Field>> classMap = new HashMap<>();
                List<Field> fields = Stream.of(cls.getDeclaredFields()).collect(Collectors.toList());
                fields.forEach(
                        field -> {
                            ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
                            if (annotation != null) {
                                String value = annotation.name();
                                if (StringUtils.isBlank(value)) {
                                    return;//return起到的作用和continue是相同的 è¯­æ³•
                                }
                                if (!classMap.containsKey(value)) {
                                    classMap.put(value, new ArrayList<>());
                                }
                                field.setAccessible(true);
                                classMap.get(value).add(field);
                            }
                        }
                );
                //索引-->columns
                Map<Integer, List<Field>> reflectionMap = new HashMap<>(16);
                //默认读取第一个sheet
                Sheet sheet = workbook.getSheetAt(0);
                boolean firstRow = true;
                for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);
                    //首行  æå–注解
                    if (firstRow) {
                        for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
                            Cell cell = row.getCell(j);
                            String cellValue = getCellValue(cell);
                            if (classMap.containsKey(cellValue)) {
                                reflectionMap.put(j, classMap.get(cellValue));
                            }
                        }
                        firstRow = false;
                    } else {
                        //忽略空白行
                        if (row == null) {
                            continue;
                        }
                        try {
                            T t = cls.newInstance();
                            //判断是否为空白行
                            boolean allBlank = true;
                            for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
                                if (reflectionMap.containsKey(j)) {
                                    Cell cell = row.getCell(j);
                                    String cellValue = getCellValue(cell);
                                    if (StringUtils.isNotBlank(cellValue)) {
                                        allBlank = false;
                                    }
                                    List<Field> fieldList = reflectionMap.get(j);
                                    fieldList.forEach(
                                            x -> {
                                                try {
                                                    handleField(t, cellValue, x);
                                                } catch (Exception e) {
                                                    log.error(String.format("reflect field:%s value:%s exception!", x.getName(), cellValue), e);
                                                }
                                            }
                                    );
                                }
                            }
                            if (!allBlank) {
                                dataList.add(t);
                            } else {
                                log.warn(String.format("row:%s is blank ignore!", i));
                            }
                        } catch (Exception e) {
                            log.error(String.format("parse row:%s exception!", i), e);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error(String.format("parse excel exception!"), e);
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (Exception e) {
                    log.error(String.format("parse excel exception!"), e);
                }
            }
        }
        return dataList;
    }
    private static <T> void handleField(T t, String value, Field field) throws Exception {
        Class<?> type = field.getType();
        if (type == null || type == void.class || StringUtils.isBlank(value)) {
            return;
        }
        if (type == Object.class) {
            field.set(t, value);
            //数字类型
        } else if (type.getSuperclass() == null || type.getSuperclass() == Number.class) {
            if (type == int.class || type == Integer.class) {
                field.set(t, NumberUtils.toInt(value));
            } else if (type == long.class || type == Long.class) {
                field.set(t, NumberUtils.toLong(value));
            } else if (type == byte.class || type == Byte.class) {
                field.set(t, NumberUtils.toByte(value));
            } else if (type == short.class || type == Short.class) {
                field.set(t, NumberUtils.toShort(value));
            } else if (type == double.class || type == Double.class) {
                field.set(t, NumberUtils.toDouble(value));
            } else if (type == float.class || type == Float.class) {
                field.set(t, NumberUtils.toFloat(value));
            } else if (type == char.class || type == Character.class) {
                field.set(t, CharUtils.toChar(value));
            } else if (type == boolean.class) {
                field.set(t, BooleanUtils.toBoolean(value));
            } else if (type == BigDecimal.class) {
                field.set(t, new BigDecimal(value));
            }
        } else if (type == Boolean.class) {
            field.set(t, BooleanUtils.toBoolean(value));
        } else if (type == Date.class) {
            field.set(t, value);
        } else if (type == String.class) {
            field.set(t, value);
        } else {
            Constructor<?> constructor = type.getConstructor(String.class);
            field.set(t, constructor.newInstance(value));
        }
    }
    private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }else{
            return StringUtils.trimToEmpty(cell.getStringCellValue());
        }
       /* if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            if (HSSFDateUtil.isCellDateFormatted(cell)) {
                return HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString();
            } else {
                return new BigDecimal(cell.getNumericCellValue()).toString();
            }
        } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            return StringUtils.trimToEmpty(cell.getStringCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
            return StringUtils.trimToEmpty(cell.getCellFormula());
        } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
            return "";
        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
            return "ERROR";
        } else {
            return cell.toString().trim();
        }*/
    }
  /*  public static <T> void writeExcel(HttpServletResponse response, List<T> dataList, Class<T> cls, String fileName) {
        Field[] fields = cls.getDeclaredFields();
        List<Field> fieldList = Arrays.stream(fields)
                .filter(field -> {
                    ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
                    if (annotation != null && annotation.col() > 0) {
                        field.setAccessible(true);
                        return true;
                    }
                    return false;
                }).sorted(Comparator.comparing(field -> {
                    int col = 0;
                    ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
                    if (annotation != null) {
                        col = annotation.col();
                    }
                    return col;
                })).collect(Collectors.toList());
        Workbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet("Sheet1");
        AtomicInteger ai = new AtomicInteger();
        {
            Row row = sheet.createRow(ai.getAndIncrement());
            AtomicInteger aj = new AtomicInteger();
            //写入头部
            fieldList.forEach(field -> {
                ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
                String columnName = "";
                if (annotation != null) {
                    columnName = annotation.value();
                }
                Cell cell = row.createCell(aj.getAndIncrement());
                CellStyle cellStyle = wb.createCellStyle();
                cellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
                Font font = wb.createFont();
                cellStyle.setFont(font);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(columnName);
            });
        }
        if (CollectionUtils.isNotEmpty(dataList)) {
            dataList.forEach(t -> {
                Row row1 = sheet.createRow(ai.getAndIncrement());
                AtomicInteger aj = new AtomicInteger();
                fieldList.forEach(field -> {
                    Class<?> type = field.getType();
                    Object value = "";
                    try {
                        value = field.get(t);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Cell cell = row1.createCell(aj.getAndIncrement());
                    if (value != null) {
                        if (type == Date.class) {
                            cell.setCellValue(value.toString());
                        } else {
                            cell.setCellValue(value.toString());
                        }
                        cell.setCellValue(value.toString());
                    }
                });
            });
        }
        //冻结窗格
        wb.getSheet("Sheet1").createFreezePane(0, 1, 0, 1);
        //浏览器下载excel
        buildExcelDocument(fileName, wb, response);
    }*/
    /**
     * æµè§ˆå™¨ä¸‹è½½excel
     *
     * @param fileName
     * @param wb
     * @param response
     */
/*
    private static void buildExcelDocument(String fileName, Workbook wb, HttpServletResponse response) {
        try {
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/
    /**
     * ç”Ÿæˆexcel文件
     *
     * @param path ç”Ÿæˆexcel路径
     * @param wb
     */
 /*   private static void buildExcelFile(String path, Workbook wb) {
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        try {
            wb.write(new FileOutputStream(file));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/
}
server/services/src/main/java/com/doumee/core/annotation/excel/ExportExcelUtils.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,88 @@
package com.doumee.core.annotation.excel;
/*
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;*/
import lombok.extern.slf4j.Slf4j;
/**
 * @Author: Melon
 * @Date: 2018/4/26
 * @Descrip:
 */
@Slf4j
public class ExportExcelUtils {
  /*  public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response){
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName, HttpServletResponse response){
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
    }
    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response){
        defaultExport(list, fileName, response);
    }
    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams,pojoClass,list);
        if (workbook != null);
        downLoadExcel(fileName, response, workbook);
    }
    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
        }
    }
    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        if (workbook != null);
        downLoadExcel(fileName, response, workbook);
    }
    public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass){
        if (StringUtils.isBlank(filePath)){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        }catch (NoSuchElementException e){
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass){
        if (file == null){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        }catch (NoSuchElementException e){
        } catch (Exception e) {
        }
        return list;
    }*/
}
server/services/src/main/java/com/doumee/core/constants/Constants.java
@@ -28,8 +28,14 @@
    public static final String FILE_DIR ="FILE_DIR" ;
    public static final String PRIVATE_KEY = "PRIVATE_KEY";
    public static String REDIS_DEBUG_STR="test_";
    public  interface MqttTopic{
        //开锁
        String openLock = "OPENLOCK";
        //关闭锁头
        String closeLock = "CLOSELOCK";
    }
  /**
    /**
   * æ•°æ®æƒé™èŒƒå›´ï¼š0只看自己;1只看自己所在校区;2看全部校区;3看指定校区(多选)
   */
  public interface PermissionType{
server/services/src/main/java/com/doumee/core/mqtt/config/MqttClientInit.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,51 @@
package com.doumee.core.mqtt.config;
import com.doumee.core.mqtt.service.MqttPushCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
public class MqttClientInit {
        static MqttClient client;
        private String userName = "doumee";
        private String passWord = "doumee@168";
        public static synchronized MqttClient getInstance(MqttConfig config,MqttPushCallback callBack){
            if(client !=null){
                return  client;
            }
            try {
                // host为主机名,clientid即连接MQTT的客户端ID,一般以唯一标识符表示,MemoryPersistence设置clientid的保存形式,默认为以内存保存
                client = new org.eclipse.paho.client.mqttv3.MqttClient(config.getHost(), config.getClientid() ,new MemoryPersistence());
                // MQTT的连接设置
                MqttConnectOptions   options = new MqttConnectOptions();
                // è®¾ç½®æ˜¯å¦æ¸…空session,这里如果设置为false表示服务器会保留客户端的连接记录,设置为true表示每次连接到服务器都以新的身份连接
                options.setCleanSession(false);
                // è®¾ç½®è¿žæŽ¥çš„用户名
                options.setUserName(config.getUsername());
                // è®¾ç½®è¿žæŽ¥çš„密码
                options.setPassword(config.getPassword().toCharArray());
                // è®¾ç½®è¶…æ—¶æ—¶é—´ å•位为秒
                options.setConnectionTimeout(10);
                // è®¾ç½®ä¼šè¯å¿ƒè·³æ—¶é—´ å•位为秒 æœåŠ¡å™¨ä¼šæ¯éš”1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
                options.setKeepAliveInterval(20);
                // è®¾ç½®å›žè°ƒ
                client.setCallback(callBack);
                //设置断开后重新连接
                options.setAutomaticReconnect(true);
                MqttTopic topic = client.getTopic(config.getClientid()+"_close");
                //遗嘱
                options.setWill(topic, "close".getBytes(), 1, true);
                client.connect(options);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return  client;
        }
}
server/services/src/main/java/com/doumee/core/mqtt/config/MqttConfig.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,34 @@
package com.doumee.core.mqtt.config;
import lombok.Data;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "mqtt")
@Data
public class MqttConfig {
        /**
         *服务器地址 ip+端口,如tcp://175.27.187.84:1883
         */
        private String host;
        /**
         * å®¢æˆ·ç«¯ç¼–码
         */
        private String clientid;
        /**
         * æŽˆæƒè´¦å·
         */
        private String username ;
        /**
         * æŽˆæƒå¯†ç 
         */
        private String password;
}
server/services/src/main/java/com/doumee/core/mqtt/service/MqttPushCallback.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,33 @@
package com.doumee.core.mqtt.service;
import com.doumee.service.business.DeviceService;
import com.doumee.service.business.DeviceSubcribeService;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MqttPushCallback implements MqttCallback {
        @Autowired
        private DeviceSubcribeService deviceSubcribeService;
        //接收消息回调
        public void connectionLost(Throwable cause) {
            // è¿žæŽ¥ä¸¢å¤±åŽï¼Œä¸€èˆ¬åœ¨è¿™é‡Œé¢è¿›è¡Œé‡è¿ž
            System.out.println("连接断开,可以做重连");
        }
        public void deliveryComplete(IMqttDeliveryToken token) {
            System.out.println("deliveryComplete---------" + token.isComplete());
        }
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            // subscribe后得到的消息会执行到这里面
            System.out.println("接收消息主题 : " + topic);
            System.out.println("接收消息Qos : " + message.getQos());
            System.out.println("接收消息内容 : " + new String(message.getPayload()));
            deviceSubcribeService.listener(new String(message.getPayload()),topic);
        }
}
server/services/src/main/java/com/doumee/core/mqtt/service/MqttToolService.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,55 @@
package com.doumee.core.mqtt.service;
import com.doumee.core.mqtt.config.MqttClientInit;
import com.doumee.core.mqtt.config.MqttConfig;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
@Service
public class MqttToolService {
    @Autowired
    private MqttConfig config;
    @Autowired
    private MqttPushCallback callBack ;
    /**
     * è®¢é˜…消息,启动加载一次
     * @param topics
     */
    public void subscribe(String[]  topics) {
        try {
            //订阅消息
            int[] Qos = new int[topics.length];//0:最多一次 ã€1:最少一次 ã€2:只有一次
            for (int i = 0; i < Qos.length; i++) {
                Qos[i] = 1;
            }
            MqttClientInit.getInstance(config,callBack).subscribe(topics, Qos);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * æ¶ˆæ¯å‘送
     * @param message
     * @param topic
     */
    public  void pubMessage(String message,String topic){
        MqttMessage mess = new MqttMessage();
        mess.setQos(1);
        mess.setRetained(true);
        mess.setPayload(message.getBytes());
        try {
            MqttClientInit.getInstance(config,callBack).publish(topic, mess);
        } catch (Exception e) {
            //LOGGER.error(e.getLocalizedMessage());
        }
    }
    public static void main(String[] args) {
        MqttToolService client1 = new MqttToolService();
        client1.pubMessage("你好啊","test");
    }
}
server/services/src/main/java/com/doumee/service/business/DeviceService.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,20 @@
package com.doumee.service.business;
import com.doumee.dao.business.model.Locks;
/**
 * ä¸Žç¡¬ä»¶å¯¹æŽ¥æœåŠ¡
 * @author æ±Ÿè¹„蹄
 * @date 2023/10/09 18:06
 */
public interface DeviceService {
    /**
     * ä¸‹å‘开车开锁指令
     * @return String
     */
    String openLock(Locks locks);
    void startSubcribe();
}
server/services/src/main/java/com/doumee/service/business/DeviceSubcribeService.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,18 @@
package com.doumee.service.business;
import com.doumee.dao.business.model.Locks;
/**
 * ä¸Žç¡¬ä»¶å¯¹æŽ¥æœåŠ¡
 * @author æ±Ÿè¹„蹄
 * @date 2023/10/09 18:06
 */
public interface DeviceSubcribeService {
    /**
     * è®¾å¤‡ä¸ŠæŠ¥æ•°æ®ï¼ˆä¸ŠæŠ¥ï¼‰
     * @param param ä¸ŠæŠ¥å‚æ•°
     */
    void listener(String param ,String topic);
}
server/services/src/main/java/com/doumee/service/business/impl/DeviceServiceImpl.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,35 @@
package com.doumee.service.business.impl;
import com.doumee.core.constants.Constants;
import com.doumee.core.mqtt.service.MqttPushCallback;
import com.doumee.core.mqtt.service.MqttToolService;
import com.doumee.dao.business.model.Locks;
import com.doumee.service.business.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
/**
 *  ä¸Žç¡¬ä»¶å¯¹æŽ¥æœåŠ¡
 * @author æ±Ÿè¹„蹄
 * @date 2023/10/09 18:06
 */
@Service
public class DeviceServiceImpl implements DeviceService {
    @Autowired
    private MqttToolService mqttToolService;
    @Override
    @PostConstruct
    public void startSubcribe() {
        mqttToolService.subscribe(new String[]{ Constants.MqttTopic.openLock, Constants.MqttTopic.closeLock});
    }
    @Override
    public String openLock(Locks locks) {
        mqttToolService.pubMessage(locks.getName(), Constants.MqttTopic.openLock);
        return null;
    }
}
server/services/src/main/java/com/doumee/service/business/impl/DeviceSubscribeServiceImpl.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,25 @@
package com.doumee.service.business.impl;
import com.doumee.core.constants.Constants;
import com.doumee.core.mqtt.service.MqttToolService;
import com.doumee.dao.business.model.Locks;
import com.doumee.service.business.DeviceService;
import com.doumee.service.business.DeviceSubcribeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
/**
 *  ä¸Žç¡¬ä»¶å¯¹æŽ¥æœåŠ¡
 * @author æ±Ÿè¹„蹄
 * @date 2023/10/09 18:06
 */
@Service
public class DeviceSubscribeServiceImpl implements DeviceSubcribeService {
    @Override
    public void listener(String param,String topic) {
        System.out.println("mqtt消息订阅==================="+param);
    }
}
server/services/src/main/resources/application-dev.yml
@@ -51,6 +51,13 @@
    notifyUrl: https://dmtest.ahapp.net/martempo_interface/web/api/wxPayNotify
    keyPath: D:/work/svn/cert/apiclient_cert.p12
########################mqtt相关配置########################
mqtt:
  host: tcp://175.27.187.84:1883
  clientid: doumeetest
  username: doumee
  password: doumee@168
tencent:
  map:
    remoteHost: https://apis.map.qq.com