test.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # ===============================================================================
  4. #
  5. # test.py
  6. #
  7. # Test program for the simple GL Viewer.
  8. #
  9. # Copyright (c) 2011, Arne Schmitz <arne.schmitz@gmx.net>
  10. # All rights reserved.
  11. #
  12. # Redistribution and use in source and binary forms, with or without
  13. # modification, are permitted provided that the following conditions are met:
  14. # * Redistributions of source code must retain the above copyright
  15. # notice, this list of conditions and the following disclaimer.
  16. # * Redistributions in binary form must reproduce the above copyright
  17. # notice, this list of conditions and the following disclaimer in the
  18. # documentation and/or other materials provided with the distribution.
  19. # * Neither the name of the <organization> nor the
  20. # names of its contributors may be used to endorse or promote products
  21. # derived from this software without specific prior written permission.
  22. #
  23. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  24. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  25. # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  26. # DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  27. # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  28. # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  29. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  30. # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  31. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  32. # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  33. #
  34. # ===============================================================================
  35. import asyncio
  36. import math
  37. import threading
  38. import time
  39. import sys
  40. from PyQt5.QtGui import *
  41. from PyQt5.QtWidgets import *
  42. from PyQt5.QtCore import *
  43. from MapGLWidget import MapGLWidget
  44. import json
  45. import dijkstra.Map as mp
  46. import ControllWidget
  47. import JointContrallerWidget
  48. import ManualOperationWidget
  49. import RobotData as RD
  50. import message_pb2 as message
  51. import google.protobuf.json_format as jtf
  52. import google.protobuf.text_format as tf
  53. from concurrent.futures import ThreadPoolExecutor
  54. import uuid
  55. from mytool.txt_helper.txt_operation import TXTOperation
  56. from custom_define import RobotName
  57. from mytool.RabbitMq_helper import async_communication as rabitmq
  58. import concurrent.futures
  59. from queue import Queue
  60. # ===============================================================================
  61. class MainWindow(QMainWindow):
  62. """docstring for Mainwindow"""
  63. mapManager = mp.MapManager()
  64. ui_nodes = {}
  65. ui_nodes["street_nodes"] = []
  66. ui_nodes["space_nodes"] = []
  67. def __init__(self, parent=None):
  68. super(MainWindow, self).__init__(parent)
  69. self.basic()
  70. self.showMaximized()
  71. self.count_frame_ = ControllWidget.CountFrame()
  72. self.isLocalTest = False
  73. self.isAutoDispatchOnline = True
  74. self.mapManager.LoadJson("./map.json")
  75. for node_id in self.mapManager.VertexDict("Base"):
  76. if node_id.find("S_") >= 0:
  77. self.ui_nodes["space_nodes"].append(node_id)
  78. if node_id.find("R_") >= 0:
  79. self.ui_nodes["street_nodes"].append(node_id)
  80. rpc_1 = "192.168.0.70:9090"
  81. mqtt_1 = ["pyui1", "192.168.0.70", 1883, "admin", "zx123456"]
  82. rpc_2 = "192.168.0.71:9090"
  83. mqtt_2 = ["pyui2", "192.168.0.71", 1883, "admin", "zx123456"]
  84. if self.isLocalTest:
  85. rpc_1 = "127.0.0.1:9090"
  86. mqtt_1 = ["pyui-main", "127.0.0.1", 1883, "admin", "zx123456"]
  87. rpc_2 = "127.0.0.1:9091"
  88. mqtt_2 = ["pyui-child", "127.0.0.1", 1883, "admin", "zx123456"]
  89. config1 = {"label": RobotName.strAGVMain,
  90. "rpc": rpc_1,
  91. "street_nodes": self.ui_nodes["street_nodes"],
  92. "space_nodes": self.ui_nodes["space_nodes"],
  93. "mqtt": mqtt_1,
  94. "subTopics": {"agv_main/agv_statu": message.RobotStatu.__name__,
  95. "agv_main/nav_statu": message.NavStatu.__name__},
  96. "cmdTopic": "agv_main/nav_cmd",
  97. "robotColor": [0.7, 0.2, 0.3]}
  98. config2 = {"label": RobotName.strAGV2,
  99. "rpc": rpc_2,
  100. # "rpc": "127.0.0.1:9091",
  101. "street_nodes": self.ui_nodes["street_nodes"],
  102. "space_nodes": self.ui_nodes["space_nodes"],
  103. "mqtt": mqtt_2,
  104. "subTopics": {"agv_child/agv_statu": message.RobotStatu.__name__,
  105. "agv_child/nav_statu": message.NavStatu.__name__},
  106. "cmdTopic": "agv_child/nav_cmd",
  107. "robotColor": [0.4, 0.2, 0.8]}
  108. self.gl = MapGLWidget() # 将opengl例子嵌入GUI
  109. self.Controller1 = ControllWidget.ControlFrame(config1)
  110. self.Controller2 = ControllWidget.ControlFrame(config2)
  111. robot_dict = {self.Controller1.robot_.name_: self.Controller1.robot_,
  112. self.Controller2.robot_.name_: self.Controller2.robot_}
  113. self.ManualOperationWidget = ManualOperationWidget.ManualOperationWidget(robot_dict)
  114. splitter_main = self.split_()
  115. self.setCentralWidget(splitter_main)
  116. self.gl.SetRobot1Instance(self.Controller1.robot_)
  117. self.gl.SetRobot2Instance(self.Controller2.robot_)
  118. self.gl.SetMaps(self.mapManager.maps)
  119. self.timer_ = QTimer()
  120. self.timer_.timeout.connect(self.Update)
  121. self.timer_.start(100)
  122. # 启动RabbitMQ
  123. self.g_rabbitmq = None
  124. if self.isAutoDispatchOnline:
  125. self.g_rabbitmq = rabitmq.RabbitAsyncCommunicator("192.168.0.201", 5672, "zx", "123456")
  126. calbbacks = [["agv_park_command_request_queue", self.recv_park_request],
  127. ["agv_pick_command_request_queue", self.recv_pick_request]]
  128. self.g_rabbitmq.Init(calbbacks, None)
  129. self.g_rabbitmq.setDaemon(True) # 守护线程随主线程结束
  130. self.g_rabbitmq.start()
  131. def recv_park_request(self, msg):
  132. print("Recv_park_request------------------\n", msg)
  133. park_table = message.park_table()
  134. try:
  135. tf.Parse(msg, park_table)
  136. except Exception as e:
  137. print("Parse error\n")
  138. return False
  139. if self.isAutoDispatchOnline:
  140. return self.AutoParkTask(park_table)
  141. return False
  142. def recv_pick_request(self, msg):
  143. print("Recv_pick_request------------------\n", msg)
  144. pick_table = message.pick_table()
  145. try:
  146. tf.Parse(msg, pick_table)
  147. except Exception as e:
  148. print("Parse error\n")
  149. return False
  150. # 加入自动任务列表
  151. '''if self.isAutoDispatchOnline:
  152. temp = time.time()
  153. self.auto_task_queue.put((2, pick_table, temp))'''
  154. if self.isAutoDispatchOnline:
  155. return self.AutoPickTask(pick_table)
  156. return False
  157. def updateMap_park(self, entrance_id, pose, wheelbase): # 0:前车轨迹,1:后车轨迹,2:添加整车轨迹
  158. self.mapManager.ResetMap("Front", 0, wheelbase / 2)
  159. [trans_x, trans_y, trans_a] = pose
  160. self.mapManager.maps["Front"].ResetVertexValue(mp.SpaceNode(entrance_id, trans_x, trans_y, trans_a))
  161. [id, x, y] = self.ComputeStreetNode("Front", entrance_id, trans_x, trans_y, trans_a)
  162. self.mapManager.maps["Front"].ResetVertexValue(mp.StreetNode(id, x, y))
  163. self.mapManager.ResetMap("Back", 0, -wheelbase / 2)
  164. [trans_x, trans_y, trans_a] = pose
  165. self.mapManager.maps["Back"].ResetVertexValue(mp.SpaceNode(entrance_id, trans_x, trans_y, trans_a))
  166. [id, x, y] = self.ComputeStreetNode("Back", entrance_id, trans_x, trans_y, trans_a)
  167. self.mapManager.maps["Back"].ResetVertexValue(mp.StreetNode(id, x, y))
  168. def asyncExecute(self, tasks):
  169. results = [feature.result() for feature in concurrent.futures.as_completed(tasks)]
  170. print("==========================\n")
  171. print(results)
  172. print("==========================\n")
  173. ret = True
  174. for result in results:
  175. ret = ret and result
  176. return ret
  177. def GetMainFrontBackAGV(self):
  178. controlMain = self.Controller1
  179. nagtive = False
  180. if controlMain.robot_.timedRobotStatu_.statu.theta < 0:
  181. nagtive = True
  182. control1 = None
  183. control2 = None
  184. if nagtive == False:
  185. control1 = self.Controller1
  186. control2 = self.Controller2
  187. else:
  188. control2 = self.Controller1
  189. control1 = self.Controller2
  190. return [controlMain, control1, control2]
  191. def AutoParkTask(self, park_table: message.park_table = None):
  192. print("AutoParkTask:---------------------\n")
  193. [controlMain, control1, control2] = self.GetMainFrontBackAGV()
  194. mainMap, frontMap, backMap = ["Base", "Front", "Back"]
  195. entrance_id = "S_" + str(park_table.terminal_id) # "S1101"
  196. entrance_x, entrance_y, entrance_theta = [park_table.entrance_measure_info.measure_info_to_plc_forward.cx,
  197. park_table.entrance_measure_info.measure_info_to_plc_forward.cy,
  198. (
  199. 90 + park_table.entrance_measure_info.measure_info_to_plc_forward.theta) / 180 * math.pi]
  200. # 变换到地图坐标系
  201. [dx, dy, da] = [-0.234040126204, -0.647539079189, 178.9302736990612 / 180 * math.pi]
  202. trans_x = -0.999825716019 * entrance_x - 0.018668506294 * entrance_y + dx
  203. trans_y = 0.018668506294 * entrance_x - 0.999825716019 * entrance_y + dy
  204. trans_a = entrance_theta + da - math.pi
  205. while trans_a < 0:
  206. trans_a += math.pi
  207. print("entrance:", entrance_id, trans_x, trans_y, trans_a / math.pi * 180)
  208. target_id = "S_" + str(park_table.allocated_space_info.table_id) # "S147"
  209. print("target:", target_id)
  210. # 轴距
  211. wheel_base = park_table.entrance_measure_info.measure_info_to_plc_forward.wheelbase
  212. control1.WheelBaseEdit.setText(str(wheel_base))
  213. control2.WheelBaseEdit.setText(str(wheel_base))
  214. trans_x += wheel_base / 2 * math.cos(trans_a)
  215. trans_y += wheel_base / 2 * math.sin(trans_a)
  216. if (controlMain.robot_.SwitchMoveMode(0, wheel_base) == False):
  217. return False
  218. autoDirect = True
  219. # # 双单车入库-----------------------------------------------------
  220. self.updateMap_park(entrance_id, [trans_x, trans_y, trans_a], wheel_base)
  221. cur_pose1 = control1.robot_.timedRobotStatu_.statu
  222. [label, pt] = self.mapManager.findNeastNode(frontMap, [cur_pose1.x, cur_pose1.y])
  223. control1.robot_.GeneratePath(label, entrance_id, frontMap)
  224. print("Front: begin:%s target:%s wheelBase:%f" % (label, entrance_id, wheel_base))
  225. cur_pose2 = control2.robot_.timedRobotStatu_.statu
  226. [label, pt] = self.mapManager.findNeastNode(backMap, [cur_pose2.x, cur_pose2.y])
  227. control2.robot_.GeneratePath(label, entrance_id, backMap)
  228. print("Back: begin:%s target:%s wheelBase:%f" % (label, entrance_id, wheel_base))
  229. threadPool = ThreadPoolExecutor(2)
  230. features = [threadPool.submit(control1.robot_.Navigatting, label, entrance_id, autoDirect, wheel_base),
  231. threadPool.submit(control2.robot_.Navigatting, label, entrance_id, autoDirect, wheel_base)]
  232. if self.asyncExecute(features) == False:
  233. print(" Park Failed ")
  234. return False
  235. print(" input entrance completed!!!!")
  236. if (controlMain.robot_.SwitchMoveMode(1, wheel_base) == False):
  237. return False
  238. controlMain.robot_.ClampClose()
  239. # 整车入库---------------------------------
  240. map_name = "Front"
  241. if controlMain.robot_.timedRobotStatu_.statu.theta < 0:
  242. map_name = "Back"
  243. controlMain.robot_.GeneratePath(entrance_id, target_id, map_name)
  244. print("begin:%s target:%s wheelBase:%f" % (entrance_id, target_id, wheel_base))
  245. controlMain.robot_.Navigatting(entrance_id, target_id, autoDirect, wheel_base)
  246. print("-------------------------")
  247. # 整车松夹池------------------------------------
  248. threadPool = ThreadPoolExecutor(1)
  249. threadPool.submit(controlMain.robot_.ClampOpen)
  250. threadPool.shutdown(wait=True)
  251. if (controlMain.robot_.SwitchMoveMode(0, wheel_base) == False):
  252. return False
  253. # 双单车出库
  254. controlMain, control1, control2 = self.GetMainFrontBackAGV()
  255. end_street = target_id.replace("S_", "R_")
  256. control1.robot_.GeneratePath(target_id, end_street, frontMap)
  257. control2.robot_.GeneratePath(target_id, end_street, backMap)
  258. threadPool = ThreadPoolExecutor(2)
  259. threadPool.submit(control1.robot_.Navigatting,
  260. target_id, end_street, autoDirect, wheel_base)
  261. threadPool.submit(control2.robot_.Navigatting,
  262. target_id, end_street, autoDirect, wheel_base)
  263. threadPool.shutdown(wait=True)
  264. # 反馈
  265. self.g_rabbitmq.publish("command_ex", "agv_park_command_response_port",
  266. tf.MessageToString(park_table, as_utf8=True))
  267. print("Publish_park_response------------------\n", park_table)
  268. return True
  269. def updateMap_pick(self, wheelBase): # 轴距
  270. self.mapManager.ResetMap("Front", 0, wheelBase / 2)
  271. self.mapManager.ResetMap("Back", 0, -wheelBase / 2)
  272. def AutoPickTask(self, pick_table: message.pick_table = None):
  273. print("AutoPickTask:---------------------\n")
  274. controlMain, control1, control2 = self.GetMainFrontBackAGV()
  275. mainMap, frontMap, backMap = ["Main", "Front", "Back"]
  276. space_id = "S_" + str(pick_table.actually_space_info.table_id) # "S147"
  277. export_id = "S_" + str(pick_table.terminal_id) # "S1101"
  278. print(space_id, export_id)
  279. # 轴距
  280. wheel_base = pick_table.actually_measure_info.measure_info_to_plc_forward.wheelbase
  281. control1.WheelBaseEdit.setText(str(wheel_base))
  282. control2.WheelBaseEdit.setText(str(wheel_base))
  283. self.updateMap_pick(wheel_base)
  284. # 双单车入库
  285. if (controlMain.robot_.SwitchMoveMode(0, wheel_base) == False):
  286. return False
  287. cur_pose1 = control1.robot_.timedRobotStatu_.statu
  288. [label, pt] = self.mapManager.findNeastNode(frontMap, [cur_pose1.x, cur_pose1.y])
  289. control1.robot_.GeneratePath(label, space_id, frontMap)
  290. print("Front: begin:%s target:%s wheelBase:%f" % (label, space_id, wheel_base))
  291. cur_pose2 = control2.robot_.timedRobotStatu_.statu
  292. [label, pt] = self.mapManager.findNeastNode(backMap, [cur_pose2.x, cur_pose2.y])
  293. control2.robot_.GeneratePath(label, space_id, backMap)
  294. print("Back: begin:%s target:%s wheelBase:%f" % (label, space_id, wheel_base))
  295. autoDirect = True
  296. threadPool = ThreadPoolExecutor(2)
  297. features = [threadPool.submit(control1.robot_.Navigatting, label, space_id, autoDirect, wheel_base),
  298. threadPool.submit(control2.robot_.Navigatting, label, space_id, autoDirect, wheel_base)]
  299. if self.asyncExecute(features) == False:
  300. print(" Pick Failed ")
  301. return False
  302. # 整车夹持------------------------------------
  303. print(" input space completed!!!!")
  304. if (controlMain.robot_.SwitchMoveMode(1, wheel_base) == False):
  305. return False
  306. if controlMain.robot_.ClampClose() == False:
  307. return False
  308. # 整车到出口---------------------------------
  309. map_name = "Front"
  310. if controlMain.robot_.timedRobotStatu_.statu.theta < 0:
  311. map_name = "Back"
  312. controlMain.robot_.GeneratePath(space_id, export_id, map_name)
  313. print("Total: begin:%s target:%s wheelBase:%f" % (space_id, export_id, wheel_base))
  314. if controlMain.robot_.Navigatting(space_id, export_id, True, wheel_base) == False:
  315. return False
  316. # 整车松夹池------------------------------------
  317. if controlMain.robot_.ClampOpen() == False:
  318. return False
  319. if (controlMain.robot_.SwitchMoveMode(1, wheel_base) == False):
  320. return False
  321. map_name = "Front"
  322. if controlMain.robot_.timedRobotStatu_.statu.theta < 0:
  323. map_name = "Back"
  324. streetNode = export_id.replace("S_", "R_")
  325. controlMain.robot_.GeneratePath(export_id, streetNode, map_name)
  326. if controlMain.robot_.Navigatting(export_id, streetNode, True, wheel_base) == False:
  327. return False
  328. # 双单车出库
  329. # controlMain, control1, control2 = self.GetMainFrontBackAGV()
  330. # self.ReLoadMap(frontMap, "./map.json")
  331. # self.updateMap_pick(export_id, frontMap)
  332. # control1.robot_.GeneratePath(export_id, "F_exportLink", frontMap)
  333. #
  334. # self.ReLoadMap(backMap, "./map.json")
  335. # self.updateMap_pick(export_id, backMap)
  336. # control2.robot_.GeneratePath(export_id, "B_exportLink", backMap)
  337. #
  338. # threadPool = ThreadPoolExecutor(2)
  339. # features=[threadPool.submit(control1.robot_.Navigatting,export_id, "F_exportLink", True, wheel_base),
  340. # threadPool.submit(control2.robot_.Navigatting,export_id, "B_exportLink", True, wheel_base)]
  341. # if self.asyncExecute(features) == False:
  342. # print(" Pick Failed ")
  343. # return False
  344. print(" over publish...")
  345. # 反馈
  346. self.g_rabbitmq.publish("command_ex", "agv_pick_command_response_port",
  347. tf.MessageToString(pick_table, as_utf8=True))
  348. print("Publish_park_response------------------\n", pick_table)
  349. return True
  350. def ComputeStreetNode(self, mapName, s_id, s_x, s_y, s_theta):
  351. """
  352. """
  353. id, n_x, n_y = "", 0, 0
  354. if s_id == "S_1101":
  355. id = "R_1101"
  356. n_y = self.mapManager.maps[mapName].graph_.points[id][1]
  357. k = math.tan(s_theta)
  358. n_x = (n_y - s_y) / k + s_x # 弧度
  359. print(id, n_x, n_y)
  360. return [id, n_x, n_y]
  361. def readJson(self, file):
  362. with open(file, 'r', encoding='utf-8') as fp:
  363. map = json.load(fp)
  364. return map
  365. def Update(self):
  366. self.gl.update()
  367. if self.isAutoDispatchOnline:
  368. # self.Controller1.setEnabled(False)
  369. # self.Controller2.setEnabled(False)
  370. pass
  371. else:
  372. self.Controller1.setVisible(True)
  373. self.Controller2.setVisible(True)
  374. # 窗口基础属性
  375. def basic(self):
  376. # 设置标题,大小,图标
  377. self.setWindowTitle("GT")
  378. self.resize(1100, 650)
  379. self.setWindowIcon(QIcon("./image/Gt.png"))
  380. # 居中显示
  381. screen = QDesktopWidget().geometry()
  382. self_size = self.geometry()
  383. self.move(int((screen.width() - self_size.width()) / 2), int((screen.height() - self_size.height()) / 2))
  384. def closeEvent(self, QCloseEvent):
  385. self.gl.close()
  386. print("close...")
  387. # 分割窗口
  388. def split_(self):
  389. splitter_main = QSplitter(Qt.Horizontal)
  390. splitter = QSplitter(Qt.Vertical)
  391. splitter.addWidget(self.count_frame_)
  392. splitter.addWidget(self.Controller1)
  393. splitter.addWidget(self.Controller2)
  394. splitter.addWidget(self.ManualOperationWidget)
  395. splitter.setStretchFactor(0, 1)
  396. splitter.setStretchFactor(1, 3)
  397. splitter.setStretchFactor(2, 3)
  398. splitter.setStretchFactor(3, 1)
  399. splitter_main.addWidget(splitter)
  400. splitter_main.addWidget(self.gl)
  401. splitter_main.setStretchFactor(0, 1)
  402. splitter_main.setStretchFactor(1, 10)
  403. return splitter_main
  404. if __name__ == "__main__":
  405. app = QApplication(sys.argv)
  406. win = MainWindow()
  407. win.show()
  408. sys.exit(app.exec_())
  409. # ===============================================================================
  410. #
  411. # Local Variables:
  412. # mode: Python
  413. # indent-tabs-mode: nil
  414. # End:
  415. #
  416. # ===============================================================================