yangys
2025-09-02 2689c8fec95018952784bd8d032afb5a194a6616
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
package org.springblade.mdm.machinefile.service;
 
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.mdm.basesetting.machine.service.MachineService;
import org.springblade.mdm.basesetting.machine.entity.Machine;
import org.springblade.mdm.commons.service.ParamService;
import org.springblade.mdm.machinefile.entity.MachineFile;
import org.springblade.mdm.program.service.ProgramAnnotationService;
import org.springblade.mdm.utils.FileContentUtil;
import org.springblade.system.pojo.entity.DictBiz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.Date;
import java.util.List;
 
@Slf4j
@Component
public class MachineFileScanService {
    @Autowired
    private MachineFileService machineFileService;
    @Autowired
    private MachineService machineService;
    @Autowired
    private ParamService paramService;
    @Autowired
    private ProgramAnnotationService programAnnotationService;
 
 
    /**
     * 扫描所有机床的配置目录
     */
    public void scanMachineFile() {
        List<Machine> machines = machineService.getEnableMachines();
        for (Machine machine : machines) {
 
            //扫描新文件
            try {
                scanDir(machine,MachineFile.DIR_TYPE_REC);
            }catch(Exception e) {
                log.error("REC扫描文件异常,机床{}", machine.getCode(), e);
            }
            try {
                scanDir(machine,MachineFile.DIR_TYPE_SEND);
            }catch(Exception e) {
                log.error("SEND扫描文件异常,机床{}", machine.getCode(), e);
            }
            try {
                scanDir(machine,MachineFile.DIR_TYPE_TEMP);
            }catch(Exception e) {
                log.error("TEMP扫描文件异常,机床{}", machine.getCode(), e);
            }
 
            //清理数据库,删除文件不存在的数据
            try {
                clearDeletedRecords(machine,MachineFile.DIR_TYPE_REC);
            }catch(Exception e) {
                log.error("REC扫描文件异常,机床{}", machine.getCode(), e);
            }
            try {
                clearDeletedRecords(machine,MachineFile.DIR_TYPE_SEND);
            }catch(Exception e) {
                log.error("SEND扫描文件异常,机床{}", machine.getCode(), e);
            }
            try {
                clearDeletedRecords(machine,MachineFile.DIR_TYPE_TEMP);
            }catch(Exception e) {
                log.error("TEMP扫描文件异常,机床{}", machine.getCode(), e);
            }
        }
 
    }
 
 
    /**
     * 扫描目录
     * @param machine 机床信息
     * @param dirType 目录类型
     * @throws IOException
     */
    public void scanDir(Machine machine,String dirType) throws IOException {
        String basePath = MachineFileService.getBasePath(machine,dirType);
        if(basePath == null) {
            log.warn("目录类型不匹配:{}",dirType);
            return;
        }
        Path dirPath = Paths.get(basePath);
        if(!dirPath.toFile().exists()){
            log.warn("扫描目录:{} 不存在",dirPath);
            return;
        }
        // 只包含普通文件
        List<Path> files = Files.list(dirPath)
            .filter(Files::isRegularFile).toList();
 
        byte[] buffer = new byte[2048];
 
        //MachineFile existFileInDb;
        List<DictBiz> annotatiionList = programAnnotationService.getAnnotionDictList();
        //boolean exists;//文件是否存在于数据库中
        for (Path filePath : files) {
            //existFileInDb = null;
            //exists = false;
 
            /*MachineFile mf = new MachineFile();
            mf.setTenantId("000000");
            mf.setName(filePath.toFile().getName());
            mf.setDirType(dirType);
            mf.setMachineCode(machine.getCode());*/
 
            try {
                //读取内容,确定程序状态
                /*int pstatus = readProgramStatus(filePath,machine.getMachineGroupCode(),annotatiionList);
                mf.setProgramStatus(pstatus);
                BasicFileAttributes attrs = Files.readAttributes(
                    filePath,
                    BasicFileAttributes.class
                );
 
                FileTime creationTime = attrs.creationTime();
                Date creationDate = new Date(creationTime.toMillis());
                mf.setFileCreateTime(creationDate);
 
                FileTime modifyTime = attrs.lastModifiedTime();
                mf.setFileModifyTime(new Date(modifyTime.toMillis()));
                mf.setFileSize(Files.size(filePath));
                try (InputStream inputStream = Files.newInputStream(filePath)) {
                    // 使用输入流读取文件内容
                    int bytesRead = inputStream.read(buffer);
                    mf.setMd5(DigestUtils.md5Hex(buffer));
                } catch (IOException e) {
                    log.error("读取文件md5失败",e);
                    continue;//有错误,掠过
                }*/
 
                MachineFile mf = readFileToMachineFile(filePath,machine,dirType,annotatiionList);
 
                machineFileService.refreshFileData(mf);
                /*
                existFileInDb = machineFileService.getExistsFile(mf.getName(),dirType,machine.getCode());
                System.out.println("文件创建时间: " + mf.getFileCreateTime());
 
                if(existFileInDb == null) {
                    machineFileService.save(mf);
                }else{
                    log.info("文件已存在:{}",filePath.getFileName());
 
                    existFileInDb.setFileSize(mf.getFileSize());
                    existFileInDb.setProgramStatus(mf.getProgramStatus());
                    existFileInDb.setFileCreateTime(mf.getFileCreateTime());
                    existFileInDb.setFileModifyTime(mf.getFileModifyTime());
                    if(!StringUtils.equals(existFileInDb.getMd5(),mf.getMd5())){
                        //文件内容发生变化了,设置状态为初始状态
                        existFileInDb.setStatus(MachineFile.STATUS_NORMAL);
                    }
                    existFileInDb.setMd5(mf.getMd5());
 
                    machineFileService.updateById(existFileInDb);
 
                }*/
            } catch (IOException e) {
                log.error("读取文件信息失败",e);
            }
 
        }
    }
 
    /**
     * 读取磁盘上的文件信息
     * @param filePath 文件路径
     * @param machine 机器
     * @param dirType 目录类型
     * @param annotatiionList 注解配置字典 用于读取程序状态
     * @return MachineFile 实例
     * @throws IOException
     */
    public MachineFile readFileToMachineFile(Path filePath,Machine machine,String dirType,List<DictBiz> annotatiionList) throws IOException {
        MachineFile mf = new MachineFile();
 
        mf.setTenantId("000000");
        mf.setName(filePath.toFile().getName());
        mf.setDirType(dirType);
        mf.setMachineCode(machine.getCode());
        mf.setProgramStatus(readProgramStatus(filePath,machine.getMachineGroupCode(),annotatiionList));
 
        BasicFileAttributes attrs = Files.readAttributes(
            filePath,
            BasicFileAttributes.class
        );
 
        FileTime creationTime = attrs.creationTime();
        Date creationDate = new Date(creationTime.toMillis());
        mf.setFileCreateTime(creationDate);
 
        FileTime modifyTime = attrs.lastModifiedTime();
        mf.setFileModifyTime(new Date(modifyTime.toMillis()));
        mf.setFileSize(Files.size(filePath));
 
        byte[] buffer = new byte[2048];
        try (InputStream inputStream = Files.newInputStream(filePath)) {
            // 使用输入流读取文件内容
            inputStream.read(buffer);
            mf.setMd5(DigestUtils.md5Hex(buffer));
        } catch (IOException e) {
            log.error("读取文件md5失败",e);
            throw new ServiceException("读取文件md5失败"+e.getMessage());
        }
 
        return mf;
    }
    /**
     * 读取文件中的程序状态
     * @param filePath 文件路径
     * @param machineGroupCode
     * @param annotatiionList 注释配置字典
     * @return 状态的整数之和
     * @throws IOException
     */
    int readProgramStatus(Path filePath,String machineGroupCode,List<DictBiz> annotatiionList) throws IOException {
        int programStatus = MachineFile.PROGRAM_STATUS_UNKNOWN;
        try(InputStream ins = Files.newInputStream(filePath);
            BufferedInputStream bis = new BufferedInputStream(ins)){
 
            boolean isText= FileContentUtil.isTextFile(bis);
            if(!isText){
                return MachineFile.PROGRAM_STATUS_UNKNOWN;
            }
            bis.reset();
            String statusLine = FileContentUtil.readLineAt(ins,ProgramAnnotationService.STATUS_LINE_INDEX);
            if(programAnnotationService.isAnnotation(statusLine,machineGroupCode,annotatiionList)){
                String progStatusTxt = programAnnotationService.removeAnnotation(machineGroupCode,statusLine,annotatiionList);
                if(ProgramAnnotationService.SQ.equals(progStatusTxt)){
                    programStatus = MachineFile.PROGRAM_STATUS_TRY;
                }else if(ProgramAnnotationService.GH.equals(progStatusTxt)){
                    programStatus = MachineFile.PROGRAM_STATUS_CURED;
                }else if(ProgramAnnotationService.PL.equals(progStatusTxt)){
                    programStatus = MachineFile.PROGRAM_STATUS_DIVIASTION;
                }
            }
        }
 
        return programStatus;
    }
 
    /**
     * 清理已经删除了文件的记录
     * @param machine
     * @param dirType
     * @throws IOException
     */
    void clearDeletedRecords(Machine machine,String dirType) throws IOException {
        List<MachineFile> machineFiles =  this.machineFileService.lambdaQuery().eq(MachineFile::getDirType,dirType)
            .eq(MachineFile::getMachineCode,machine.getCode()).list();
 
        String basePath = MachineFileService.getBasePath(machine,dirType);
        if(basePath == null) {
            log.warn("目录类型不匹配:{}",dirType);
            return;
        }
        Path dirPath = Paths.get(basePath);
        if(!dirPath.toFile().exists()){
            log.warn("扫描目录:{} 不存在",dirPath);
            return;
        }
 
        List<Path> files = Files.list(dirPath)
            .filter(Files::isRegularFile).toList();
 
        for(MachineFile mf : machineFiles){
            long findCount = files.stream().filter(filePath -> filePath.toFile().getName().equals(mf.getName())).count();
            if(findCount == 0){
                //文件夹内没找到,需要删除记录
                mf.markFileDeleted();
                this.machineFileService.updateById(mf);
            }
        }
    }
}