Преглед на файлове

设备程序管理问题修改

yejian преди 2 години
родител
ревизия
d2afab9ebb

+ 85 - 9
imcs-admin-boot/imcs-business-biz/src/main/java/com/github/zuihou/business/productionResourceCenter/service/impl/ProgramServiceImpl.java

@@ -1,5 +1,6 @@
 package com.github.zuihou.business.productionResourceCenter.service.impl;
 
+import cn.hutool.core.collection.CollectionUtil;
 import cn.hutool.core.util.StrUtil;
 import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
@@ -8,6 +9,7 @@ import com.github.zuihou.base.service.SuperServiceImpl;
 import com.github.zuihou.business.DemoLine.DemoLineConstant;
 import com.github.zuihou.business.productionReadyCenter.entity.BBomProcedureTool;
 import com.github.zuihou.business.productionReadyCenter.entity.BomProcedure;
+import com.github.zuihou.business.productionReadyCenter.entity.BomProcedureProductionresource;
 import com.github.zuihou.business.productionReadyCenter.service.BomProcedureToolService;
 import com.github.zuihou.business.productionResourceCenter.dao.ProductionresourceBizMapper;
 import com.github.zuihou.business.productionResourceCenter.dao.ProgramMapper;
@@ -20,6 +22,7 @@ import com.github.zuihou.business.productionResourceCenter.entity.Tool;
 import com.github.zuihou.business.productionResourceCenter.service.ProgramService;
 import com.github.zuihou.business.productionResourceCenter.service.ProgramSuitProductionresourceService;
 import com.github.zuihou.common.constant.UrlConfConstant;
+import com.github.zuihou.common.util.Scpclient;
 import com.github.zuihou.context.BaseContextHandler;
 import com.github.zuihou.database.mybatis.auth.DataScope;
 import com.github.zuihou.database.mybatis.conditions.Wraps;
@@ -27,11 +30,14 @@ import com.github.zuihou.database.mybatis.conditions.query.LbqWrapper;
 import com.github.zuihou.file.entity.Attachment;
 import com.github.zuihou.file.properties.FileServerProperties;
 import com.github.zuihou.file.service.AttachmentService;
+import com.github.zuihou.tenant.entity.Module;
 import com.github.zuihou.tenant.service.CodeRuleService;
+import com.github.zuihou.tenant.service.ModuleService;
 import com.github.zuihou.utils.BeanPlusUtil;
 import com.xxl.job.core.util.FileUtil;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.MediaType;
@@ -39,13 +45,13 @@ import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 import org.springframework.web.client.RestTemplate;
 
+import java.io.File;
 import java.nio.file.Paths;
 import java.time.LocalDate;
+import java.time.LocalDateTime;
 import java.time.format.DateTimeFormatter;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
+import java.util.stream.Collectors;
 
 import static com.github.zuihou.utils.DateUtils.DEFAULT_MONTH_FORMAT_SLASH;
 
@@ -61,6 +67,12 @@ import static com.github.zuihou.utils.DateUtils.DEFAULT_MONTH_FORMAT_SLASH;
 @Slf4j
 @Service
 public class ProgramServiceImpl extends SuperServiceImpl<ProgramMapper, Program> implements ProgramService {
+    @Value("${zuihou.file.storage-path}")
+    private String uploadFolder;
+    @Value("${zuihou.nginx.ip}")
+    private String nginxIp;
+    @Value("${zuihou.nginx.port}")
+    private String nginxPort;
     @Autowired
     ProgramSuitProductionresourceService programSuitProductionresourceService;
     @Autowired
@@ -78,6 +90,8 @@ public class ProgramServiceImpl extends SuperServiceImpl<ProgramMapper, Program>
 
     @Autowired
     private BomProcedureToolService bomProcedureToolService;
+    @Autowired
+    private ModuleService moduleService;
 
     @Override
     public IPage<Program> pageList(IPage page, LbqWrapper<Program> wrapper) {
@@ -108,8 +122,7 @@ public class ProgramServiceImpl extends SuperServiceImpl<ProgramMapper, Program>
         headers.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));
         HttpEntity<String> formEntity = new HttpEntity<String>(jsonParam, headers);
         //调用接口
-        String returnData = restTemplate.postForObject(UrlConfConstant.plcURL, formEntity, String.class);
-
+//        String returnData = restTemplate.postForObject(UrlConfConstant.plcURL, formEntity, String.class);
 
         Program program = BeanPlusUtil.toBean(data, Program.class);
         //根据编码规则
@@ -152,7 +165,17 @@ public class ProgramServiceImpl extends SuperServiceImpl<ProgramMapper, Program>
     @Transactional(rollbackFor = Exception.class)
     public Boolean delete(Program model) {
 
-        return removeById(model.getId());
+        Productionresource productionresource = productionresourceMapper.selectById(model.getResourceId());
+
+        removeById(model.getId());
+        //设置程序数量
+        List<Program>programList = baseMapper.selectList(Wraps.<Program>lbQ().eq(Program::getResourceId,model.getResourceId()));
+
+        if(productionresource!=null){
+            productionresource.setProgramNum(programList.size());
+            productionresourceMapper.updateById(productionresource);
+        }
+        return true;
     }
 
     @Override
@@ -237,13 +260,65 @@ public class ProgramServiceImpl extends SuperServiceImpl<ProgramMapper, Program>
     @Override
     public Boolean synchronousNumericalProgram(Program data){
         if (data.getResourceList() != null && data.getResourceList().size() > 0){
-            // 先查找设备ip,端口
-            //
+            List<Productionresource> productionresources = productionresourceMapper.selectList(Wraps.<Productionresource>lbQ().in(Productionresource::getId,data.getResourceList()));
+            List<Long> moduldIds = productionresources.stream().map(p -> p.getModuleId()).collect(Collectors.toList());
+            List<Module> modules = moduleService.list(Wraps.<Module>lbQ().in(Module::getId,moduldIds));
+            Map<Long, List<Module>> moduleMap = new HashMap<Long, List<Module>>();
+            if(CollectionUtil.isNotEmpty(modules)){
+                moduleMap = modules.stream().collect(Collectors.groupingBy(Module::getId));
+            }
+            for(Productionresource productionresource : productionresources){
+                // 根据不同系统查找数控程序
+                // TODO 真实机床调试 Scpclient
+                List<String> fileNames = new ArrayList<>();
+                String ip = productionresource.getIp();
+                String port = productionresource.getPort();
+                String userName = "";
+                String password = "";
+                Scpclient scpclient = new Scpclient(ip,Integer.valueOf(port),userName,password);
+                List<Module> resourceModules = moduleMap.get(productionresource.getModuleId());
+                if(CollectionUtil.isNotEmpty(resourceModules)){
+                    Module resourceModule = resourceModules.get(0);
+                    String cncSystem = resourceModule.getCncSystem().getKey();
+                    String cncFilePath = resourceModule.getCncFilePath();
+                    // 模拟现在直接nginx下查找文件同步
+                    fileNames = scpclient.getSubfolderName(cncFilePath);
+                }
+                if(CollectionUtil.isNotEmpty(fileNames)){
+                    uploadFolder = uploadFolder + "0000/cncFile/";
+                    for(String fileName : fileNames){
+                        scpclient.getFile(fileName,uploadFolder);
+                        // 入库设备程序表
+                        Program program = new Program();
+                        program.setResourceId(productionresource.getId());
+                        program.setName(productionresource.getName());
+                        program.setNo(productionresource.getCode());
+                        String cncFilePath = "http://" + nginxIp + ":" + nginxPort + "/file/0000/cncFile/" + fileName;
+                        program.setFilePath(cncFilePath);
+                        program.setSource("2");
+                        program.setSynTime(LocalDateTime.now());
+                        //根据编码规则
+                        save(program);
+                    }
+
+                    //设置程序数量
+                    List<Program>programList = baseMapper.selectList(Wraps.<Program>lbQ().eq(Program::getResourceId,productionresource.getId()));
+
+                    if(productionresource!=null){
+                        productionresource.setProgramNum(programList.size());
+                        productionresourceMapper.updateById(productionresource);
+                    }
+                }
+
+
+            }
+
         }
 
         return null;
     }
 
+    @Override
     public Boolean equipmentDelete(Program data){
         if(1==1){//调用删除接口
             baseMapper.deleteById(data.getId());
@@ -252,6 +327,7 @@ public class ProgramServiceImpl extends SuperServiceImpl<ProgramMapper, Program>
 
     }
 
+    @Override
     public Map implementProgram(Program data){
 
         return null;

+ 2 - 2
imcs-admin-boot/imcs-business-entity/src/main/java/com/github/zuihou/business/productionResourceCenter/entity/Productionresource.java

@@ -94,7 +94,7 @@ public class Productionresource extends Entity<Long> {
     @Length(max = 32, message = "模块ID长度不能超过32")
     @TableField(value = "module_id", condition = LIKE)
     @Excel(name = "模块ID")
-    private String moduleId;
+    private Long moduleId;
 
     /**
      * 名称
@@ -313,7 +313,7 @@ public class Productionresource extends Entity<Long> {
     @Builder
     public Productionresource(Long id, LocalDateTime createTime, Long createUser, LocalDateTime updateTime, Long updateUser,
                               Long tenantId, Long productionlineId, Long boxId, RemoteData<String, String> type, RemoteData<String, String>  category,
-                              String moduleId, String name, String code, String status, String remark, String resourcesType, String onlineStatus, String ip, String port) {
+                              Long moduleId, String name, String code, String status, String remark, String resourcesType, String onlineStatus, String ip, String port) {
         this.id = id;
         this.createTime = createTime;
         this.createUser = createUser;

+ 188 - 0
imcs-admin-boot/imcs-common/src/main/java/com/github/zuihou/common/util/Scpclient.java

@@ -0,0 +1,188 @@
+package com.github.zuihou.common.util;
+
+import java.io.*;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import ch.ethz.ssh2.*;
+
+public class Scpclient {
+
+    static private Scpclient instance;
+
+    private String ip;
+    private int port;
+    private String username;
+    private String password;
+    public String getUsername () {
+        return username;
+    }
+    public void setUsername (String username){
+        this.username = username;
+    }
+    public String getPassword () {
+        return password;
+    }
+    public void setPassword (String password){
+        this.password = password;
+    }
+    public int getPort () {
+        return port;
+    }
+    public void setPort ( int port){
+        this.port = port;
+    }
+
+    static synchronized public Scpclient getInstance(String IP, int port,
+                                                     String username, String passward) {
+        if (instance == null) {
+            instance = new Scpclient(IP, port, username, passward);
+        }
+        return instance;
+    }
+
+    public Scpclient(String IP, int port, String username, String passward) {
+        this.ip = IP;
+        this.port = port;
+        this.username = username;
+        this.password = passward;
+    }
+
+    public void getFile(String remoteFile, String localTargetDirectory) {
+        Connection conn = new Connection(ip, port);
+        try {
+            conn.connect();
+            boolean isAuthenticated = conn.authenticateWithPassword(username,
+                    password);
+            if (isAuthenticated == false) {
+                System.err.println("authentication failed");
+            }
+            SCPClient client = new SCPClient(conn);
+            client.get(remoteFile, localTargetDirectory);
+            conn.close();
+        } catch (IOException ex) {
+            Logger.getLogger(SCPClient.class.getName()).log(Level.SEVERE, null, ex);
+        }
+    }
+
+    public void putFile (String localFile, String remoteTargetDirectory){
+        Connection conn = new Connection(ip, port);
+        try {
+            conn.connect();
+            boolean isAuthenticated = conn.authenticateWithPassword(username,
+                    password);
+            if (isAuthenticated == false) {
+                System.err.println("authentication failed");
+            }
+            SCPClient client = new SCPClient(conn);
+            client.put(localFile, remoteTargetDirectory);
+            conn.close();
+        } catch (IOException ex) {
+            Logger.getLogger(SCPClient.class.getName()).log(Level.SEVERE, null, ex);
+        }
+    }
+
+    public void putFile (String localFile, String remoteFileName, String remoteTargetDirectory, String mode){
+        Connection conn = new Connection(ip, port);
+        try {
+            conn.connect();
+            boolean isAuthenticated = conn.authenticateWithPassword(username,
+                    password);
+            if (isAuthenticated == false) {
+                System.err.println("authentication failed");
+            }
+            SCPClient client = new SCPClient(conn);
+            if ((mode == null) || (mode.length() == 0)) {
+                mode = "0600";
+            }
+            client.put(localFile, remoteFileName, remoteTargetDirectory, mode);
+            //重命名
+            ch.ethz.ssh2.Session sess = conn.openSession();
+            String tmpPathName = remoteTargetDirectory + File.separator + remoteFileName;
+            String newPathName = tmpPathName.substring(0, tmpPathName.lastIndexOf("."));
+            sess.execCommand("mv " + remoteFileName + " " + newPathName);//重命名回来
+            conn.close();
+        } catch (IOException ex) {
+            Logger.getLogger(SCPClient.class.getName()).log(Level.SEVERE, null, ex);
+        }
+    }
+    public static byte[] getBytes (String filePath){
+        byte[] buffer = null;
+        try {
+            File file = new File(filePath);
+            FileInputStream fis = new FileInputStream(file);
+            ByteArrayOutputStream byteArray = new ByteArrayOutputStream(1024 * 1024);
+            byte[] b = new byte[1024 * 1024];
+            int i;
+            while ((i = fis.read(b)) != -1) {
+                byteArray.write(b, 0, i);
+            }
+            fis.close();
+            byteArray.close();
+            buffer = byteArray.toByteArray();
+        } catch (FileNotFoundException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return buffer;
+    }
+
+    /**
+     * 得到服务器上指定文件夹下所有子文件夹(第一级子文件夹)
+     * @return
+     */
+    public List<String> getSubfolderName(String targetFolder) {
+        List<String> folderNameList = new ArrayList<String>();
+        try {
+            // 创建一个连接实例
+            Connection connection = new Connection(ip, port);
+            // 连接
+            connection.connect();
+            // 认证
+            boolean isAuthenticated = connection.authenticateWithPassword(username, password);
+            // 创建一个会话
+            Session sess = connection.openSession();
+            sess.requestPTY("bash");
+            sess.startShell();
+            InputStream stdout = new StreamGobbler(sess.getStdout());
+            InputStream stderr = new StreamGobbler(sess.getStderr());
+            BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdout));
+            BufferedReader stderrReader = new BufferedReader(new InputStreamReader(stderr));
+            //向服务器上输入命令
+            PrintWriter out = new PrintWriter(sess.getStdin());
+            //进入文件存放的目录
+            out.println("cd " + targetFolder);
+            out.println("ll");
+            out.println("exit");
+            out.close();
+            sess.waitForCondition(ChannelCondition.CLOSED|ChannelCondition.EOF | ChannelCondition.EXIT_STATUS,30000);
+
+            //本机查看远程操作的指令及状态
+            System.out.println("输入指令后对应的显示信息:");
+            while (true) {
+                String line = stdoutReader.readLine();
+                if (line == null){
+                    break;
+                }
+                //获取文件名称
+                //取出正确的文件名称
+                StringBuffer sb = new StringBuffer(line.substring(line.lastIndexOf(":")+3, line.length()));
+                folderNameList.add(line);
+            }
+            //关闭连接
+            sess.close();
+            connection.close();
+            stderrReader.close();
+            stdoutReader.close();
+        } catch (IOException e) {
+            e.printStackTrace(System.err);
+            System.exit(2);
+        }
+        return folderNameList;
+    }
+}
+
+

+ 1 - 1
imcs-admin-boot/imcs-file-biz/src/main/java/com/github/zuihou/file/service/impl/AttachmentServiceImpl.java

@@ -92,7 +92,7 @@ public class AttachmentServiceImpl extends SuperServiceImpl<AttachmentMapper, At
             file = fileStrategy.uploadOriFileName(multipartFile);
             //将程序通过FTP传递一份
             boolean flag = ftpProperties.upload(multipartFile.getInputStream(),multipartFile.getOriginalFilename());
-            Assert.isFalse(flag,"通过Ftp传输程序文件失败!");
+            Assert.isFalse(!flag,"通过Ftp传输程序文件失败!");
         }else{
             file = fileStrategy.upload(multipartFile);
         }

+ 4 - 2
imcs-admin-boot/imcs-tenant-biz/src/main/java/com/github/zuihou/tenant/service/impl/ProductionresourceServiceImpl.java

@@ -826,6 +826,7 @@ public class ProductionresourceServiceImpl extends SuperCacheServiceImpl<Product
         try{
             Map <String,Map> equipMap = getEquipListByInterface();
 
+            List<Map> finalReturnList = returnList;
             list.stream().map((item) -> {
                 //把三种状态,拼对象进去
 //            String linkStatus = item.get("linkStatus")==null?"0":item.get("linkStatus").toString();
@@ -848,10 +849,10 @@ public class ProductionresourceServiceImpl extends SuperCacheServiceImpl<Product
 
                     if(StringUtils.isNotBlank(searchProductionStatus)){
                         if(searchProductionStatus.equals(productionStatus)){
-                            returnList.add(item);
+                            finalReturnList.add(item);
                         }
                     }else{
-                        returnList.add(item);
+                        finalReturnList.add(item);
                     }
 
                 }else {
@@ -867,6 +868,7 @@ public class ProductionresourceServiceImpl extends SuperCacheServiceImpl<Product
             }).collect(Collectors.toList());
         }catch (Exception e){
             e.printStackTrace();
+            returnList = list;
         }
         return  returnList;
     }