From d2aa9473613af8cd99c3a6dea0331765ecb830dc Mon Sep 17 00:00:00 2001 From: luxiaotao1123 <t1341870251@163.com> Date: 星期二, 17 十二月 2024 13:57:20 +0800 Subject: [PATCH] # --- zy-acs-fake/src/main/resources/unlock.py | 22 +++ zy-acs-manager/src/main/resources/agv.py | 174 ++++++++++++++---------- zy-acs-fake/src/main/java/com/zy/acs/fake/config/RedisProperties.java | 96 +++++++++++++ zy-acs-fake/src/main/java/com/zy/acs/fake/service/MapService.java | 78 +++++++++++ zy-acs-manager/src/main/java/com/zy/acs/manager/core/service/MapService.java | 2 5 files changed, 299 insertions(+), 73 deletions(-) diff --git a/zy-acs-fake/src/main/java/com/zy/acs/fake/config/RedisProperties.java b/zy-acs-fake/src/main/java/com/zy/acs/fake/config/RedisProperties.java new file mode 100644 index 0000000..4ac338f --- /dev/null +++ b/zy-acs-fake/src/main/java/com/zy/acs/fake/config/RedisProperties.java @@ -0,0 +1,96 @@ +package com.zy.acs.fake.config; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +import java.net.InetAddress; +import java.net.UnknownHostException; + +/** + * redis绯荤粺閰嶇疆 + * Created by vincent on 2018/10/15 + */ +@Configuration +@ConfigurationProperties(prefix = "redis") +public class RedisProperties { + + public static String HOST_NAME; + + static { + try { + HOST_NAME = InetAddress.getLocalHost().getHostName(); + } catch (UnknownHostException e) { + System.err.println("find hostname err"); + } + } + + private String host; + + private String password; + + private int port; + + private int min; + + private int max; + + private int timeout; + + private int index; + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + 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; + } + + public int getMin() { + return min; + } + + public void setMin(int min) { + this.min = min; + } + + public int getMax() { + return max; + } + + public void setMax(int max) { + this.max = max; + } + + public int getTimeout() { + return timeout; + } + + public void setTimeout(int timeout) { + this.timeout = timeout; + } + + public int getIndex() { + return index; + } + + public void setIndex(int index) { + this.index = index; + } +} diff --git a/zy-acs-fake/src/main/java/com/zy/acs/fake/service/MapService.java b/zy-acs-fake/src/main/java/com/zy/acs/fake/service/MapService.java index 1578c7a..6228265 100644 --- a/zy-acs-fake/src/main/java/com/zy/acs/fake/service/MapService.java +++ b/zy-acs-fake/src/main/java/com/zy/acs/fake/service/MapService.java @@ -1,11 +1,21 @@ package com.zy.acs.fake.service; +import com.zy.acs.fake.config.RedisProperties; import com.zy.acs.fake.domain.DynamicNode; import com.zy.acs.framework.common.Cools; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; import org.springframework.stereotype.Component; +import org.springframework.util.StopWatch; +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.List; @@ -18,9 +28,73 @@ @Autowired private MapDataDispatcher mapDataDispatcher; + @Autowired + private RedisProperties redisProperties; + + public synchronized void unlockPath0(String agvNo, String codeData) { + try { + + Resource resource = new ClassPathResource("unlock.py"); + File tempScript = null; + + InputStream is = resource.getInputStream(); + tempScript = File.createTempFile("unlock", ".py"); + tempScript.deleteOnExit(); + + Files.copy(is, tempScript.toPath(), StandardCopyOption.REPLACE_EXISTING); + tempScript.setExecutable(true); + + ProcessBuilder processBuilder = new ProcessBuilder( + "python" + , tempScript.getAbsolutePath() + , redisProperties.getHost() + , redisProperties.getPassword() + , String.valueOf(redisProperties.getPort()) + , String.valueOf(redisProperties.getIndex()) + , agvNo + , codeData + ); + + processBuilder.redirectErrorStream(true); + + Process process = processBuilder.start(); + + BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); + String line; + StringBuilder builder = new StringBuilder(); + while ((line = reader.readLine()) != null) { + builder.append(line); + } + + int exitCode = process.waitFor(); + if (exitCode != 0) { + log.error("Python script exited with error code: {}", exitCode); + log.error("python error:{}", builder.toString()); + return; + } + reader.close(); + + if (builder.length() <= 0) { + return; + } + + String result = builder.toString(); + + if (!Cools.isEmpty(result)) { + if (!"1".equals(result)) { + log.error("Fail python"); + } + } + + + } catch (Exception e) { + log.error("MapService.unlockPath", e); + } + } public synchronized void unlockPath(String agvNo, String codeData) { try { + long startTime = System.currentTimeMillis(); if (Cools.isEmpty(agvNo, codeData)) { return; @@ -55,8 +129,10 @@ mapDataDispatcher.clearDynamicMatrixByCodeList(lev, resetCodeList); } + log.info("瑙i攣璺緞鍑芥暟鑺辫垂鏃堕棿涓猴細{}姣......", System.currentTimeMillis() - startTime); + } catch (Exception e) { - log.error("TrafficService.unlockPath", e); + log.error("MapService.unlockPath", e); } } diff --git a/zy-acs-fake/src/main/resources/unlock.py b/zy-acs-fake/src/main/resources/unlock.py new file mode 100644 index 0000000..33be43f --- /dev/null +++ b/zy-acs-fake/src/main/resources/unlock.py @@ -0,0 +1,22 @@ +import numpy as np +import json +import time +import redis + +startTime = time.perf_counter() + +redisHost = sys.argv[1] +redisPwd = sys.argv[2] +redisPort = sys.argv[3] +redisIdx = sys.argv[4] + +agvNo = sys.argv[5] +codeData = sys.argv[6] + +# 鍒涘缓涓�涓繛鎺ユ睜 +pool = redis.ConnectionPool(host=redisHost, port=int(redisPort), password=redisPwd, db=int(redisIdx)) +r = redis.Redis(connection_pool=pool) + +codeMatrixStr = r.get('KV.AGV_MAP_ASTAR_CODE_FLAG.1') +codeMatrix = np.array(json.loads(codeMatrixStr)) + diff --git a/zy-acs-manager/src/main/java/com/zy/acs/manager/core/service/MapService.java b/zy-acs-manager/src/main/java/com/zy/acs/manager/core/service/MapService.java index d50cad9..aa8bb1c 100644 --- a/zy-acs-manager/src/main/java/com/zy/acs/manager/core/service/MapService.java +++ b/zy-acs-manager/src/main/java/com/zy/acs/manager/core/service/MapService.java @@ -227,7 +227,7 @@ } } catch (Exception e) { - log.error("TrafficService.unlockPath", e); + log.error("MapService.unlockPath", e); } } diff --git a/zy-acs-manager/src/main/resources/agv.py b/zy-acs-manager/src/main/resources/agv.py index a366634..2634411 100644 --- a/zy-acs-manager/src/main/resources/agv.py +++ b/zy-acs-manager/src/main/resources/agv.py @@ -1,13 +1,12 @@ import ast import sys - import numpy as np import json import time import redis +from collections import deque radiusLen = None - # 灏嗗瓧绗︿覆杞崲涓烘诞鐐瑰瀷鏁扮粍 def convert_to_float_array(str_array): @@ -15,50 +14,63 @@ return np.array(ast.literal_eval(str_array), dtype=float) return str_array -def getWaveScopeByCode(x, y): - code = codeMatrix[x, y] +def getWaveScopeByCode_iterative(x, y): + """ + 浣跨敤骞垮害浼樺厛鎼滅储锛圔FS锛夋潵浠f浛閫掑綊锛屼互閬垮厤閫掑綊娣卞害杩囧ぇ鐨勯棶棰樸�� + """ includeList = [] existNodes = set() - spreadWaveNode({"x": x, "y": y}, {"x": x, "y": y}, existNodes, includeList) - return includeList + queue = deque() -def spreadWaveNode(originNode, currNode, existNodes, includeList): - x, y = currNode['x'], currNode['y'] - neighbors = [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)] - for neighbor in neighbors: - extendNeighborNodes(originNode, {"x": neighbor[0], "y": neighbor[1]}, existNodes, includeList) - -def extendNeighborNodes(originNode, nextNode, existNodes, includeList): - x, y = nextNode['x'], nextNode['y'] - if (x < 0 or x >= codeMatrix.shape[0] or y < 0 or y >= codeMatrix.shape[1]): - return - - if (x, y) in existNodes: - return - + originNode = {"x": x, "y": y} + currNode = {"x": x, "y": y} + queue.append(currNode) existNodes.add((x, y)) - nextNodeCodeData = codeMatrix[x, y] + while queue: + node = queue.popleft() + node_x, node_y = node['x'], node['y'] + neighbors = [ + (node_x + 1, node_y), + (node_x - 1, node_y), + (node_x, node_y + 1), + (node_x, node_y - 1) + ] - if nextNodeCodeData == 'NONE': - spreadWaveNode(originNode, nextNode, existNodes, includeList) - else: - o1Cda = convert_to_float_array(cdaMatrix[originNode['x'], originNode['y']]) - o2Cda = convert_to_float_array(cdaMatrix[x, y]) + for neighbor in neighbors: + nx, ny = neighbor + # 妫�鏌ヨ竟鐣屾潯浠� + if (nx < 0 or nx >= codeMatrix.shape[0] or ny < 0 or ny >= codeMatrix.shape[1]): + continue + if (nx, ny) in existNodes: + continue - num1 = (o1Cda[0] - o2Cda[0]) ** 2 - num2 = (o1Cda[1] - o2Cda[1]) ** 2 - if num1 + num2 <= radiusLen ** 2: - includeList.append({"x": int(x), "y": int(y), "code": str(codeMatrix[x, y])}) - spreadWaveNode(originNode, nextNode, existNodes, includeList) + existNodes.add((nx, ny)) + neighbor_code = codeMatrix[nx, ny] -# 鎵惧埌鏌愪釜鍊煎搴旂殑 x, y 涓嬫爣 + if neighbor_code == 'NONE': + queue.append({"x": nx, "y": ny}) + else: + o1Cda = convert_to_float_array(cdaMatrix[x, y]) + o2Cda = convert_to_float_array(cdaMatrix[nx, ny]) + + num1 = (o1Cda[0] - o2Cda[0]) ** 2 + num2 = (o1Cda[1] - o2Cda[1]) ** 2 + if num1 + num2 <= radiusLen ** 2: + includeList.append({ + "x": int(nx), + "y": int(ny), + "code": str(codeMatrix[nx, ny]) + }) + queue.append({"x": nx, "y": ny}) + + return includeList + def find_value_in_matrix(value): indices = np.where(codeMatrix == value) return list(zip(indices[0], indices[1])) def initWaveMatrix(): - lev = 1 waveMatrix = np.empty_like(codeMatrix, dtype=object) for x in range(codeMatrix.shape[0]): @@ -73,7 +85,10 @@ # 浼樺寲鐗堟湰锛氫娇鐢ㄩ泦鍚堟潵鎻愰珮鎬ц兘 def mergeWave(originWave, vehicle): # 灏嗗瓧绗︿覆瑙f瀽涓洪泦鍚� - set_data = set(ast.literal_eval(originWave)) + try: + set_data = set(ast.literal_eval(originWave)) + except (ValueError, SyntaxError): + set_data = set() # 濡傛灉 vehicle 涓嶅湪闆嗗悎涓紝鍒欐坊鍔� set_data.add(vehicle) # 杩斿洖搴忓垪鍖栧悗鐨勫瓧绗︿覆 @@ -90,6 +105,8 @@ # 浣跨敤 numpy 鍔犻�熺殑浠g爜 def process_dynamic_matrix(dynamicMatrix, codeMatrix): + global waveMatrix # 纭繚 waveMatrix 鏄叏灞�鍙橀噺 + # 灏� dynamicMatrix 杞崲涓虹粨鏋勫寲鏁扮粍 dynamicMatrix = convert_to_structured_array(dynamicMatrix) @@ -104,57 +121,72 @@ # 閬嶅巻婊¤冻鏉′欢鐨勫潗鏍� for x, y in zip(x_indices, y_indices): - # print(code) - data = dynamicMatrix[x][y] - vehicle = data['vehicle'] - includeList = getWaveScopeByCode(x,y) + vehicle = dynamicMatrix[x][y]['vehicle'] + includeList = getWaveScopeByCode_iterative(x, y) for include in includeList: originWave = waveMatrix[include['x']][include['y']] waveMatrix[include['x']][include['y']] = mergeWave(originWave, vehicle) -radiusLenStr = sys.argv[1] -radiusLen = float(radiusLenStr) +def main(): + global radiusLen, codeMatrix, cdaMatrix, waveMatrix # 澹版槑涓哄叏灞�鍙橀噺 -redisHost = sys.argv[2] -redisPwd = sys.argv[3] -redisPort = sys.argv[4] -redisIdx = sys.argv[5] + if len(sys.argv) != 6: + print("Usage: python script.py <radiusLen> <redisHost> <redisPwd> <redisPort> <redisIdx>") + sys.exit(1) -startTime = time.perf_counter() + radiusLenStr = sys.argv[1] + radiusLen = float(radiusLenStr) -# 鍒涘缓涓�涓繛鎺ユ睜 -pool = redis.ConnectionPool(host=redisHost, port=int(redisPort), password=redisPwd, db=int(redisIdx)) -r = redis.Redis(connection_pool=pool) + redisHost = sys.argv[2] + redisPwd = sys.argv[3] + redisPort = sys.argv[4] + redisIdx = sys.argv[5] -codeMatrixStr = r.get('KV.AGV_MAP_ASTAR_CODE_FLAG.1') -codeMatrix = np.array(json.loads(codeMatrixStr)) + startTime = time.perf_counter() -cdaMatrixStr = r.get('KV.AGV_MAP_ASTAR_CDA_FLAG.1') -cdaMatrix = np.array(json.loads(cdaMatrixStr)) + # 鍒涘缓涓�涓繛鎺ユ睜 + pool = redis.ConnectionPool(host=redisHost, port=int(redisPort), password=redisPwd, db=int(redisIdx)) + r = redis.Redis(connection_pool=pool) -dynamicMatrixStr = r.get('KV.AGV_MAP_ASTAR_DYNAMIC_FLAG.1') -dynamicMatrix = np.array(json.loads(dynamicMatrixStr)) + # 鑾峰彇骞跺姞杞� codeMatrix + codeMatrixStr = r.get('KV.AGV_MAP_ASTAR_CODE_FLAG.1') + if codeMatrixStr is None: + print("Error: 'KV.AGV_MAP_ASTAR_CODE_FLAG.1' not found in Redis.") + sys.exit(1) + codeMatrix = np.array(json.loads(codeMatrixStr)) -waveMatrix = initWaveMatrix() + # 鑾峰彇骞跺姞杞� cdaMatrix + cdaMatrixStr = r.get('KV.AGV_MAP_ASTAR_CDA_FLAG.1') + if cdaMatrixStr is None: + print("Error: 'KV.AGV_MAP_ASTAR_CDA_FLAG.1' not found in Redis.") + sys.exit(1) + cdaMatrix = np.array(json.loads(cdaMatrixStr)) -# # 浣跨敤 numpy 鍔犻�熺殑浠g爜 -process_dynamic_matrix(dynamicMatrix, codeMatrix) + # 鑾峰彇骞跺姞杞� dynamicMatrix + dynamicMatrixStr = r.get('KV.AGV_MAP_ASTAR_DYNAMIC_FLAG.1') + if dynamicMatrixStr is None: + print("Error: 'KV.AGV_MAP_ASTAR_DYNAMIC_FLAG.1' not found in Redis.") + sys.exit(1) + dynamicMatrix = np.array(json.loads(dynamicMatrixStr)) -# for x in range(dynamicMatrix.shape[0]): -# for y in range(dynamicMatrix.shape[1]): -# data = dynamicMatrix[x, y] -# vehicle = data['vehicle'] -# if vehicle != '0' and vehicle != '-1': -# getWaveScopeByCode(x, y) + # 鍒濆鍖� waveMatrix + waveMatrix = initWaveMatrix() -# 灏� numpy.ndarray 杞崲涓哄祵濂楀垪琛� -waveMatrixList = waveMatrix.tolist() -# 灏嗗祵濂楀垪琛ㄨ浆鎹负 JSON 瀛楃涓� -waveMatrixJsonStr = json.dumps(waveMatrixList) + # 澶勭悊 dynamicMatrix + process_dynamic_matrix(dynamicMatrix, codeMatrix) -r.set("KV.AGV_MAP_ASTAR_WAVE_FLAG.1",waveMatrixJsonStr) + # 灏� numpy.ndarray 杞崲涓哄祵濂楀垪琛� + waveMatrixList = waveMatrix.tolist() + # 灏嗗祵濂楀垪琛ㄨ浆鎹负 JSON 瀛楃涓� + waveMatrixJsonStr = json.dumps(waveMatrixList) -end = time.perf_counter() -# print('绋嬪簭杩愯鏃堕棿涓�: %s Seconds' % (end - startTime)) -print("1") + # 灏嗙粨鏋滀繚瀛樺洖 Redis + r.set("KV.AGV_MAP_ASTAR_WAVE_FLAG.1", waveMatrixJsonStr) + end = time.perf_counter() + # 鎵撳嵃绋嬪簭杩愯鏃堕棿 +# print(f"绋嬪簭杩愯鏃堕棿涓�: {end - startTime} Seconds") + print("1") + +if __name__ == "__main__": + main() \ No newline at end of file -- Gitblit v1.9.1