RobotData.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  1. import copy
  2. import enum
  3. import time
  4. from numpy import fabs
  5. import message_pb2 as message
  6. import grpc
  7. import message_pb2_grpc as msg_rpc
  8. from ManualOperationWidget import ManualOperationType
  9. from custom_define import RobotName, ActType
  10. from mqtt_async import MqttAsync
  11. import google.protobuf.json_format as jtf
  12. import json
  13. from dijkstra.Map import SpaceNode, StreetNode, MapManager, DijikstraMap
  14. import uuid
  15. import random
  16. import math
  17. import Count
  18. from sigmoid import sigmoid
  19. class TimeStatu:
  20. def __init__(self, statu=None, timeout=3):
  21. self.statu = statu
  22. self.time = time.time()
  23. self.timeout_s = timeout
  24. def timeout(self):
  25. tm = time.time()
  26. return tm - self.time > self.timeout_s or self.statu == None
  27. class Robot(MqttAsync):
  28. def __init__(self, rpc_ipport, name=""):
  29. MqttAsync.__init__(self)
  30. self.test_speed = 0
  31. self.timedRobotStatu_ = TimeStatu(message.RobotStatu, 0)
  32. self.timedNavStatu_ = TimeStatu(message.NavStatu, 0)
  33. self.dataTopic_ = {}
  34. self.rpc_ipport_ = rpc_ipport
  35. self.messageArrivedSignal = None
  36. self.currentNavData_ = None
  37. self.navCmdTopic_ = None
  38. if (name == RobotName.strAGVMain):
  39. self.speedCmdTopic = "monitor_child/speedcmd"
  40. else:
  41. self.speedCmdTopic = "monitor_child/speedcmd"
  42. self.currentNavPathNodes_ = None
  43. self.currentNavPath_ = None
  44. # 当前正在执行的流程默认0,存车1, 取车2
  45. self.current_sequence_: int = 0
  46. self.pathColor_ = [1, 1, 0]
  47. self.robotColor_ = [0.7, 0.2, 0.3] # agv当前颜色
  48. self.name_ = name
  49. self.begId_ = "------"
  50. self.targetId_ = "------"
  51. self.autoTest_ = False
  52. self.l_ = 0.8 # 轮长
  53. self.L_ = 2.9 # 轴距
  54. self.W_ = 2.5 # 宽
  55. self.heat_ = 0 # 心跳
  56. self.manual_status = ManualOperationType.eReady # 正在进行的手动操作
  57. self.manual_speed = [0.0, 0]
  58. def Color(self):
  59. if self.IsMainModeStatu():
  60. return [0, 0, 0]
  61. return self.robotColor_
  62. def IsMainAgv(self):
  63. if self.timedNavStatu_.timeout() == False:
  64. if self.timedNavStatu_.statu.main_agv == True:
  65. return True
  66. return False
  67. def IsMainModeStatu(self):
  68. if self.IsMainAgv():
  69. if self.timedNavStatu_.timeout() == False:
  70. if self.timedNavStatu_.statu.move_mode == 1:
  71. return True
  72. return False
  73. def SetSubDataTopic(self, match: dict, messageSignal=None):
  74. self.dataTopic_ = match
  75. self.messageArrivedSignal = messageSignal
  76. for item in match.items():
  77. [topic, _] = item
  78. self.subscribe(topic, self.on_message)
  79. def SetCmdTopic(self, topic):
  80. self.navCmdTopic_ = topic
  81. def SetColor(self, pathColor, robotColor):
  82. self.pathColor_ = pathColor
  83. self.robotColor_ = robotColor
  84. def ResetPose(self, agv: message.RobotStatu):
  85. self.timedRobotStatu_ = TimeStatu(agv, 2)
  86. def ResetNavStatu(self, statu: message.NavStatu):
  87. self.timedNavStatu_ = TimeStatu(statu, 2)
  88. def on_message(self, client, userdata, msg):
  89. topic = msg.topic
  90. if self.dataTopic_.get(topic) is not None:
  91. dtype = self.dataTopic_[topic]
  92. if dtype == message.RobotStatu.__name__:
  93. proto = message.RobotStatu()
  94. jtf.Parse(msg.payload.decode(), proto)
  95. self.ResetPose(proto)
  96. if dtype == message.NavStatu.__name__:
  97. self.last_running = self.IsNavigating()
  98. proto = message.NavStatu()
  99. jtf.Parse(msg.payload.decode(), proto)
  100. self.ResetNavStatu(proto)
  101. if self.last_running == True and self.IsNavigating() == False:
  102. self.currentNavPathNodes_ = None
  103. self.currentNavPath_ = None
  104. if self.messageArrivedSignal is not None:
  105. self.messageArrivedSignal()
  106. def MpcSelectTraj(self):
  107. traj = []
  108. if self.timedNavStatu_.timeout() == False:
  109. nav = self.timedNavStatu_.statu
  110. for pose2d in nav.selected_traj.poses:
  111. traj.append([pose2d.x, pose2d.y, pose2d.theta])
  112. return traj
  113. def MpcPredictTraj(self):
  114. traj = []
  115. if self.timedNavStatu_.timeout() == False:
  116. nav = self.timedNavStatu_.statu
  117. for pose2d in nav.predict_traj.poses:
  118. traj.append([pose2d.x, pose2d.y, pose2d.theta])
  119. return traj
  120. def Connected(self):
  121. return self.timedNavStatu_.timeout() == False and self.timedRobotStatu_.timeout() == False
  122. def IsNavigating(self):
  123. return not self.ActionType() == ActType.eReady
  124. '''if self.timedNavStatu_.timeout() == False:
  125. key = self.timedNavStatu_.statu.key
  126. if key == "" or key == None:
  127. return False
  128. return True'''
  129. def GeneratePath(self, begID, endID, mapName):
  130. self.currentNavPathNodes_ = MapManager().GetShortestPath(mapName, begID, endID)
  131. # if task_type == "DoubleAGV":
  132. # print("AdjustPath------------------")
  133. # if self.IsMainModeStatu() is False:
  134. # print("原始路径:")
  135. # for node in self.currentNavPathNodes_:
  136. # print(node.id_, node.y_)
  137. # self.currentNavPathNodes_ = self.AdjustPath(self.currentNavPathNodes_)
  138. # print("修改路径:")
  139. # for node in self.currentNavPathNodes_:
  140. # print(node.id_, node.y_)
  141. self.currentNavPath_ = DijikstraMap().CreatePath(self.currentNavPathNodes_, 0.5)
  142. if self.currentNavPathNodes_ is not None and self.currentNavPath_ is not None:
  143. self.begId_ = begID
  144. self.targetId_ = endID
  145. return True
  146. return False
  147. def PositionId(self):
  148. if self.timedRobotStatu_.timeout():
  149. return None
  150. x = self.timedRobotStatu_.statu.x
  151. y = self.timedRobotStatu_.statu.y
  152. djks_map = MapManager()
  153. [label, pt] = djks_map.findNeastNode([x, y])
  154. return [label, pt]
  155. '''
  156. 阻塞直到导航完成
  157. '''
  158. def Navigatting(self, begId, targetId, autoDirect, wheelbase=0, task_type: int = 0):
  159. if wheelbase < 2.4 or wheelbase > 3.2:
  160. print("wheelbase is out of range!\n")
  161. return False
  162. print("nav")
  163. self.SetSequence(task_type)
  164. # self.ExecPathNodes(autoDirect)
  165. if self.ExecNavtask(autoDirect, wheelbase) == False:
  166. self.ResetSequence()
  167. return False
  168. self.ResetSequence()
  169. if self.IsMainModeStatu():
  170. Count.TestCount().loadCountAdd()
  171. else:
  172. Count.TestCount().singleCountAdd()
  173. return True
  174. def AutoTestNavClamp(self, begId, targetId):
  175. beg = begId
  176. target = targetId
  177. while self.autoTest_:
  178. if self.TestNavClampOnce(beg, target) == False:
  179. print(" quit auto Test")
  180. break
  181. print("1111")
  182. posInfo = self.PositionId()
  183. if posInfo is not None:
  184. [label, pt] = posInfo
  185. beg = label
  186. print("beg", beg)
  187. node = MapManager().GetVertex(beg)
  188. if node is not None:
  189. if isinstance(node, (SpaceNode)):
  190. target = "O"
  191. if isinstance(node, (StreetNode)):
  192. end_nodes = ["E", "B", "C", "D"]
  193. id = random.randint(0, 1000) % 4
  194. target = end_nodes[id]
  195. print("3333", target)
  196. print(" Next nav clamp cmd,%s to %s" % (beg, target))
  197. def ActionType(self):
  198. if self.timedNavStatu_.timeout() == False:
  199. runningStatu = self.timedNavStatu_.statu
  200. if runningStatu.statu == 0:
  201. return ActType.eReady
  202. if runningStatu.statu == 1:
  203. return ActType.eRotation
  204. if runningStatu.statu == 2:
  205. return ActType.eHorizon
  206. if runningStatu.statu == 3:
  207. return ActType.eVertical
  208. if runningStatu.statu == 4:
  209. return ActType.eMPC
  210. if runningStatu.statu == 5:
  211. return ActType.eClampClose
  212. if runningStatu.statu == 6:
  213. return ActType.eClampOpen
  214. if runningStatu.statu == 7:
  215. return ActType.eLifterRise
  216. if runningStatu.statu == 8:
  217. return ActType.eLifterDown
  218. else:
  219. return ActType.eReady
  220. @staticmethod
  221. def generateProtoNode(node):
  222. protoNode = message.PathNode()
  223. protoNode.x = node.x_
  224. protoNode.y = node.y_
  225. protoNode.id = node.id_
  226. return protoNode
  227. def ExecNavtask(self, autoDirect, wheelbase=0):
  228. cmd = message.NavCmd()
  229. key = str(uuid.uuid4())
  230. cmd.key = key
  231. cmd.action = 0
  232. cmd.sequence = self.current_sequence_
  233. actions = self.SplitPath(self.currentNavPathNodes_)
  234. for action in actions:
  235. [type, nodes] = action
  236. if type == "input":
  237. [street, space] = nodes
  238. protoSpace = self.generateProtoNode(space)
  239. protoStreet = self.generateProtoNode(street)
  240. act = message.NewAction()
  241. act.type = 1
  242. act.wheelbase = wheelbase
  243. act.spaceNode.CopyFrom(protoSpace)
  244. act.streetNode.CopyFrom(protoStreet)
  245. cmd.newActions.add().CopyFrom(act)
  246. if type == "output":
  247. [space, street] = nodes
  248. protoSpace = self.generateProtoNode(space)
  249. protoStreet = self.generateProtoNode(street)
  250. act = message.NewAction()
  251. act.type = 2
  252. act.wheelbase = wheelbase
  253. act.spaceNode.CopyFrom(protoSpace)
  254. act.streetNode.CopyFrom(protoStreet)
  255. cmd.newActions.add().CopyFrom(act)
  256. if type == "nav":
  257. action = self.CreateNavPathNodesAction(nodes, autoDirect)
  258. if action is None:
  259. print("Nav cmd is None")
  260. return False
  261. else:
  262. cmd.newActions.add().CopyFrom(action)
  263. print(cmd)
  264. if cmd is None:
  265. print("Nav cmd is None")
  266. return False
  267. channel = grpc.insecure_channel(self.rpc_ipport_)
  268. stub = msg_rpc.NavExcutorStub(channel)
  269. response = stub.Start(cmd)
  270. print("client received: ", response)
  271. if not response.ret == 0:
  272. print("nav failed :%s" % (response.info))
  273. return False
  274. else:
  275. print("nav completed !!!")
  276. return True
  277. def CreateNavPathNodesAction(self, path, autoDirect):
  278. # if path is not None and self.timedRobotStatu_.timeout() == False:
  279. if 1:
  280. for node in path:
  281. if isinstance(node, (SpaceNode)):
  282. print(" nodes must all street node")
  283. return None
  284. statu = self.timedRobotStatu_.statu
  285. # if statu is not None:
  286. if 1:
  287. newAction = message.NewAction()
  288. size = len(path)
  289. for i in range(size):
  290. node = path[i]
  291. pathNode = message.PathNode()
  292. pathNode.x = node.x_
  293. pathNode.y = node.y_
  294. pathNode.id = node.id_
  295. newAction.type = 4
  296. if autoDirect:
  297. newAction.type = 3
  298. newAction.pathNodes.add().CopyFrom(pathNode)
  299. return newAction
  300. else:
  301. print("statu is None")
  302. else:
  303. print("current path is none")
  304. return None
  305. def ExecPathNodes(self, autoDirect):
  306. if self.navCmdTopic_ == None:
  307. print("Robot has not set nav cmd topic")
  308. return False
  309. if not self.ActionType() == ActType.eReady:
  310. print(" robot is navigating ,key:%s" % (self.timedNavStatu_.statu.key))
  311. return False
  312. cmd = message.NavCmd()
  313. key = str(uuid.uuid4())
  314. cmd.key = key
  315. cmd.action = 0
  316. action = self.CreateNavPathNodesAction(self.currentNavPathNodes_, autoDirect)
  317. if action is None:
  318. print("Nav cmd is None")
  319. return False
  320. cmd.newActions.add().CopyFrom(action)
  321. print(cmd)
  322. channel = grpc.insecure_channel(self.rpc_ipport_)
  323. stub = msg_rpc.NavExcutorStub(channel)
  324. response = stub.Start(cmd)
  325. return True
  326. '''
  327. 根据AGV单车的起始位置调整路径
  328. '''
  329. def AdjustPath(self, path):
  330. adjusted_path = copy.deepcopy(path)
  331. y_offset = 1.2
  332. dy = 0
  333. # if self.IsMainAgv() or self.name_ == "AgvMain":
  334. if self.name_ == RobotName.strAGVMain:
  335. dy = 1
  336. # if not self.IsMainAgv() or self == "AGV2":
  337. if self.name_ == RobotName.strAGV2:
  338. dy = -1
  339. print("dy:", dy)
  340. for node in adjusted_path:
  341. if isinstance(node, StreetNode):
  342. if dy > 0:
  343. node.y_ += y_offset
  344. elif dy < 0:
  345. node.y_ -= y_offset
  346. else:
  347. pass
  348. return adjusted_path
  349. '''
  350. 拆分路径,生成动作集,input:入库动作,nav:导航动作,output:出库动作
  351. '''
  352. def SplitPath(self, path):
  353. space_count = 0
  354. for i in range(len(path)):
  355. if isinstance(path[i], (SpaceNode)):
  356. space_count += 1
  357. if i == 0 or i == len(path) - 1:
  358. pass
  359. else:
  360. print("Error: space node is not first/last of path")
  361. return None
  362. actions = []
  363. lastNode = None
  364. navIndex = -1
  365. for node in path:
  366. if lastNode == None:
  367. lastNode = node
  368. continue
  369. if isinstance(node, (SpaceNode)): # 当前点是车位点
  370. if isinstance(lastNode, (SpaceNode)): # 上一点为车位点
  371. print("Error: last node and current node is space node ")
  372. lastNode = None
  373. continue
  374. elif isinstance(lastNode, (StreetNode)): # 上一点为马路点,则动作为入库
  375. actions.append(["input", [lastNode, node]])
  376. lastNode = None
  377. continue
  378. if isinstance(node, (StreetNode)):
  379. if isinstance(lastNode, (SpaceNode)): # 上一点为车位点, 出库
  380. actions.append(["output", [lastNode, node]])
  381. elif isinstance(lastNode, (StreetNode)):
  382. if navIndex < 0:
  383. actions.append(["nav", [lastNode]])
  384. navIndex = len(actions) - 1
  385. actions[navIndex][1].append(node)
  386. lastNode = node
  387. return actions
  388. def SwitchMoveMode(self, mode, wheelbase):
  389. if self.IsMainAgv() == False:
  390. print(" this agv is single can not switch mode")
  391. return False
  392. cmd = message.NavCmd()
  393. key = str(uuid.uuid4())
  394. cmd.key = key
  395. cmd.action = 0
  396. action = message.NewAction()
  397. action.type = 8
  398. action.changedMode = mode
  399. if mode == 1:
  400. action.wheelbase = wheelbase
  401. cmd.newActions.add().CopyFrom(action)
  402. print(cmd)
  403. channel = grpc.insecure_channel(self.rpc_ipport_)
  404. stub = msg_rpc.NavExcutorStub(channel)
  405. response = stub.Start(cmd)
  406. return True
  407. def IsClampClosed(self):
  408. if self.timedRobotStatu_.timeout() == False:
  409. if self.IsMainModeStatu():
  410. clamp = self.timedRobotStatu_.statu.agvStatu.clamp
  411. clamp_other = self.timedRobotStatu_.statu.agvStatu.clamp_other
  412. return (clamp == 1 and clamp_other == 1)
  413. else:
  414. return self.timedRobotStatu_.statu.agvStatu.clamp == 1
  415. return False
  416. def IsClampRunning(self):
  417. if self.timedRobotStatu_.timeout() == False:
  418. if self.IsMainModeStatu():
  419. clamp = self.timedRobotStatu_.statu.agvStatu.clamp
  420. clamp_other = self.timedRobotStatu_.statu.agvStatu.clamp_other
  421. return (clamp == 0 or clamp_other == 0)
  422. else:
  423. return self.timedRobotStatu_.statu.agvStatu.clamp == 0
  424. return False
  425. def IsClampOpened(self):
  426. if self.timedRobotStatu_.timeout() == False:
  427. if self.IsMainModeStatu():
  428. clamp = self.timedRobotStatu_.statu.agvStatu.clamp
  429. clamp_other = self.timedRobotStatu_.statu.agvStatu.clamp_other
  430. return (clamp == 2 and clamp_other == 2)
  431. else:
  432. return self.timedRobotStatu_.statu.agvStatu.clamp == 2
  433. return False
  434. def ClampClose(self):
  435. if self.IsClampClosed() == True:
  436. print("clamp closed")
  437. return True
  438. cmd = message.NavCmd()
  439. cmd.action = 0
  440. key = str(uuid.uuid4())
  441. cmd.key = (key)
  442. act = message.NewAction()
  443. act.type = 6
  444. cmd.newActions.add().CopyFrom(act)
  445. channel = grpc.insecure_channel(self.rpc_ipport_)
  446. stub = msg_rpc.NavExcutorStub(channel)
  447. response = stub.Start(cmd)
  448. return True
  449. def ClampOpen(self):
  450. if self.IsClampOpened() == True:
  451. print("clamp opended")
  452. return True
  453. cmd = message.NavCmd()
  454. cmd.action = 0
  455. key = str(uuid.uuid4())
  456. cmd.key = (key)
  457. act = message.NewAction()
  458. act.type = 7
  459. cmd.newActions.add().CopyFrom(act)
  460. channel = grpc.insecure_channel(self.rpc_ipport_)
  461. stub = msg_rpc.NavExcutorStub(channel)
  462. response = stub.Start(cmd)
  463. return True
  464. def IsLiferDowned(self):
  465. if self.timedRobotStatu_.timeout() == False:
  466. if self.IsMainModeStatu():
  467. lifter = self.timedRobotStatu_.statu.agvStatu.lifter
  468. lifter_other = self.timedRobotStatu_.statu.agvStatu.lifter_other
  469. return (lifter == 2 and lifter_other == 2)
  470. else:
  471. return self.timedRobotStatu_.statu.agvStatu.lifter == 2
  472. return False
  473. def IsLiferRunning(self):
  474. if self.timedRobotStatu_.timeout() == False:
  475. if self.IsMainModeStatu():
  476. lifter = self.timedRobotStatu_.statu.agvStatu.lifter
  477. lifter_other = self.timedRobotStatu_.statu.agvStatu.lifter_other
  478. return (lifter == 0 and lifter_other == 0)
  479. else:
  480. return self.timedRobotStatu_.statu.agvStatu.lifter == 0
  481. return False
  482. def IsLiferRose(self):
  483. if self.timedRobotStatu_.timeout() == False:
  484. if self.IsMainModeStatu():
  485. lifter = self.timedRobotStatu_.statu.agvStatu.lifter
  486. lifter_other = self.timedRobotStatu_.statu.agvStatu.lifter_other
  487. return (lifter == 1 and lifter_other == 1)
  488. else:
  489. return self.timedRobotStatu_.statu.agvStatu.lifter == 1
  490. return False
  491. def LiferRise(self):
  492. if self.IsLiferRose() == True:
  493. print("lifter has rose")
  494. return True
  495. cmd = message.NavCmd()
  496. cmd.action = 0
  497. key = str(uuid.uuid4())
  498. cmd.key = (key)
  499. act = message.NewAction()
  500. act.type = 9
  501. cmd.newActions.add().CopyFrom(act)
  502. channel = grpc.insecure_channel(self.rpc_ipport_)
  503. stub = msg_rpc.NavExcutorStub(channel)
  504. response = stub.Start(cmd)
  505. return True
  506. def LiferDown(self):
  507. if self.IsLiferDowned() == True:
  508. print("lifter has downed")
  509. return True
  510. cmd = message.NavCmd()
  511. cmd.action = 0
  512. key = str(uuid.uuid4())
  513. cmd.key = (key)
  514. act = message.NewAction()
  515. act.type = 10
  516. cmd.newActions.add().CopyFrom(act)
  517. channel = grpc.insecure_channel(self.rpc_ipport_)
  518. stub = msg_rpc.NavExcutorStub(channel)
  519. response = stub.Start(cmd)
  520. return True
  521. def CancelNavTask(self):
  522. cmd = message.NavCmd()
  523. cmd.action = 3
  524. channel = grpc.insecure_channel(self.rpc_ipport_)
  525. stub = msg_rpc.NavExcutorStub(channel)
  526. response = stub.Cancel(cmd)
  527. print("client received: ", response)
  528. print(" Cancel task completed!!!")
  529. return True
  530. def IsManualTaskRunning(self):
  531. return self.manual_status != ManualOperationType.eReady
  532. def ManualTask(self, current_operation, step_acc=0, speed=0):
  533. if self.IsNavigating():
  534. print("AGV is navigating!!!")
  535. # return False
  536. # slowly stop
  537. if current_operation == ManualOperationType.eReady and \
  538. ManualOperationType.eReady < self.manual_status <= ManualOperationType.eRightMove:
  539. print("Manual_Unit_SlowlyStop")
  540. self.Manual_Unit_SlowlyStop(current_operation, speed)
  541. return True
  542. # if self.IsManualTaskRunning():
  543. # return print("ManualTask | ManualTask is running...")
  544. self.manual_status = current_operation
  545. if ManualOperationType.eReady < current_operation <= ManualOperationType.eRightMove:
  546. cmd = message.ToAgvCmd()
  547. self.heat_ += 1
  548. self.heat_ %= 255
  549. cmd.H1 = self.heat_
  550. if self.IsMainModeStatu():
  551. cmd.M1 = 1
  552. else:
  553. cmd.M1 = 0
  554. if current_operation == ManualOperationType.eCounterclockwiseRotate:
  555. cmd.T1 = 1
  556. cmd.V1 = 0
  557. cmd.W1 = speed / 180 * math.pi * sigmoid(step_acc, 0, 1)
  558. if current_operation == ManualOperationType.eClockwiseRotate:
  559. cmd.T1 = 1
  560. cmd.V1 = 0
  561. cmd.W1 = -speed / 180 * math.pi * sigmoid(step_acc, 0, 1)
  562. if current_operation == ManualOperationType.eForwardMove:
  563. cmd.T1 = 3
  564. cmd.V1 = speed * sigmoid(step_acc, 0, 1)
  565. cmd.W1 = 0
  566. if current_operation == ManualOperationType.eBackwardMove:
  567. cmd.T1 = 3
  568. cmd.V1 = -speed * sigmoid(step_acc, 0, 1)
  569. cmd.W1 = 0
  570. if current_operation == ManualOperationType.eLeftMove:
  571. cmd.T1 = 2
  572. cmd.V1 = speed * sigmoid(step_acc, 0, 1)
  573. cmd.W1 = 0
  574. if current_operation == ManualOperationType.eRightMove:
  575. cmd.T1 = 2
  576. cmd.V1 = -speed * sigmoid(step_acc, 0, 1)
  577. cmd.W1 = 0
  578. cmd.V2 = cmd.V1
  579. cmd.V3 = cmd.V1
  580. cmd.W2 = cmd.W1
  581. cmd.W3 = cmd.W1
  582. cmd.L1 = self.L_
  583. cmd.P1 = 0
  584. cmd.D1 = 0.0
  585. cmd.end = 1
  586. self.manual_speed = [cmd.V1, cmd.W1]
  587. # 处理为json格式
  588. cmd_dict = {}
  589. for field in cmd.DESCRIPTOR.fields:
  590. cmd_dict[field.name] = field.default_value
  591. for field, value in cmd.ListFields():
  592. cmd_dict[field.name] = value
  593. cmd_json = json.dumps(cmd_dict, indent=None, separators=(',', ':'))
  594. self.publish(self.speedCmdTopic, cmd_json)
  595. print(cmd_json)
  596. # channel = grpc.insecure_channel(self.rpc_ipport_)
  597. # stub = msg_rpc.NavExcutorStub(channel)
  598. # response = stub.ManualOperation(cmd_0)
  599. # print("client received: ", response)
  600. # self.manual_status = ManualOperationType.eReady
  601. # print("ManualOperation {op_type} task completed!!!".format(op_type=hex(current_operation)))
  602. time.sleep(0.05)
  603. return True
  604. elif ManualOperationType.eClampClose <= current_operation <= ManualOperationType.eClampOpen:
  605. self.Manual_Unit_Clamp(current_operation)
  606. return True
  607. elif ManualOperationType.eLifterRise <= current_operation <= ManualOperationType.eLifterDown:
  608. self.Manual_Unit_Lifter(current_operation)
  609. return True
  610. return False
  611. def Manual_Unit_Lifter(self, current_operation: ManualOperationType):
  612. print(current_operation)
  613. cmd = message.ToAgvCmd()
  614. self.heat_ += 1
  615. self.heat_ %= 255
  616. cmd.H1 = self.heat_
  617. if self.IsMainModeStatu():
  618. cmd.M1 = 1
  619. else:
  620. cmd.M1 = 0
  621. cmd.T1 = self.ManualOperationType2AgvCmdType(current_operation)
  622. # 处理为json格式 # jtf.MessageToJson(cmd)
  623. cmd_dict = {}
  624. for field in cmd.DESCRIPTOR.fields:
  625. cmd_dict[field.name] = field.default_value
  626. for field, value in cmd.ListFields():
  627. cmd_dict[field.name] = value
  628. cmd_json = json.dumps(cmd_dict, indent=None, separators=(',', ':'))
  629. self.publish(self.speedCmdTopic, cmd_json)
  630. print(cmd_json)
  631. # self.manual_status = ManualOperationType.eReady
  632. return True
  633. def Manual_Unit_Clamp(self, current_operation: ManualOperationType):
  634. print(current_operation)
  635. cmd = message.ToAgvCmd()
  636. self.heat_ += 1
  637. self.heat_ %= 255
  638. cmd.H1 = self.heat_
  639. if self.IsMainModeStatu():
  640. cmd.M1 = 1
  641. else:
  642. cmd.M1 = 0
  643. cmd.T1 = self.ManualOperationType2AgvCmdType(current_operation)
  644. # 处理为json格式 # jtf.MessageToJson(cmd)
  645. cmd_dict = {}
  646. for field in cmd.DESCRIPTOR.fields:
  647. cmd_dict[field.name] = field.default_value
  648. for field, value in cmd.ListFields():
  649. cmd_dict[field.name] = value
  650. cmd_json = json.dumps(cmd_dict, indent=None, separators=(',', ':'))
  651. self.publish(self.speedCmdTopic, cmd_json)
  652. print(cmd_json)
  653. # self.manual_status = ManualOperationType.eReady
  654. return True
  655. def ManualOperationType2AgvCmdType(self, mo_type: ManualOperationType):
  656. if mo_type == ManualOperationType.eLifterRise:
  657. return ActType.eLifterRise
  658. if mo_type == ManualOperationType.eLifterDown:
  659. return ActType.eLifterDown
  660. if mo_type == ManualOperationType.eClampClose:
  661. return ActType.eClampClose
  662. if mo_type == ManualOperationType.eClampOpen:
  663. return ActType.eClampOpen
  664. def Manual_Unit_SlowlyStop(self, current_operation: ManualOperationType, speed):
  665. step_sum = 10
  666. step_acc = 1
  667. speed_v = max(fabs(self.manual_speed[0]), 0.01)
  668. speed_w = max(fabs(self.manual_speed[1]), 1)
  669. while step_acc <= step_sum:
  670. if ManualOperationType.eReady < self.manual_status <= ManualOperationType.eRightMove:
  671. cmd = message.ToAgvCmd()
  672. self.heat_ += 1
  673. self.heat_ %= 255
  674. cmd.H1 = self.heat_
  675. if self.IsMainModeStatu():
  676. cmd.M1 = 1
  677. else:
  678. cmd.M1 = 0
  679. if self.manual_status == ManualOperationType.eCounterclockwiseRotate:
  680. cmd.T1 = 1
  681. cmd.V1 = 0
  682. cmd.W1 = speed_w / 180 * math.pi * (step_sum - step_acc) / step_sum
  683. if self.manual_status == ManualOperationType.eClockwiseRotate:
  684. cmd.T1 = 1
  685. cmd.V1 = 0
  686. cmd.W1 = -speed_w / 180 * math.pi * (step_sum - step_acc) / step_sum
  687. if self.manual_status == ManualOperationType.eForwardMove:
  688. cmd.T1 = 3
  689. cmd.V1 = speed_v * (step_sum - step_acc) / step_sum
  690. cmd.W1 = 0
  691. if self.manual_status == ManualOperationType.eBackwardMove:
  692. cmd.T1 = 3
  693. cmd.V1 = -speed_v * (step_sum - step_acc) / step_sum
  694. cmd.W1 = 0
  695. if self.manual_status == ManualOperationType.eLeftMove:
  696. cmd.T1 = 2
  697. cmd.V1 = speed_v * (step_sum - step_acc) / step_sum
  698. cmd.W1 = 0
  699. if self.manual_status == ManualOperationType.eRightMove:
  700. cmd.T1 = 2
  701. cmd.V1 = -speed_v * (step_sum - step_acc) / step_sum
  702. cmd.W1 = 0
  703. cmd.V2 = cmd.V1
  704. cmd.V3 = cmd.V1
  705. cmd.W2 = cmd.W1
  706. cmd.W3 = cmd.W1
  707. cmd.L1 = self.L_
  708. cmd.end = 1
  709. # 处理为json格式
  710. cmd_dict = {}
  711. for field in cmd.DESCRIPTOR.fields:
  712. cmd_dict[field.name] = field.default_value
  713. for field, value in cmd.ListFields():
  714. cmd_dict[field.name] = value
  715. cmd_json = json.dumps(cmd_dict, indent=None, separators=(',', ':'))
  716. self.publish(self.speedCmdTopic, cmd_json)
  717. print(cmd_json)
  718. step_acc += 1
  719. time.sleep(0.1)
  720. self.manual_status = ManualOperationType.eReady
  721. self.manual_speed = [0, 0]
  722. print("Manual_Unit_SlowlyStop completed.")
  723. return True
  724. # def GenerateActionMPC(self, beg_name, end_name, autoDirect, wheelbase=0, task_type="None"):
  725. # self.GeneratePath(beg_name, end_name)
  726. # actions = list()
  727. #
  728. # split_path = self.SplitPath(self.currentNavPathNodes_)
  729. # for action in split_path:
  730. # [type, nodes] = action
  731. # if type == "input":
  732. # [street, space] = nodes
  733. # protoSpace = self.generateProtoNode(space)
  734. # protoStreet = self.generateProtoNode(street)
  735. # act = message.NewAction()
  736. # act.type = 1
  737. # act.wheelbase = wheelbase
  738. # act.spaceNode.CopyFrom(protoSpace)
  739. # act.streetNode.CopyFrom(protoStreet)
  740. #
  741. # actions.append(act)
  742. # if type == "output":
  743. # [space, street] = nodes
  744. # protoSpace = self.generateProtoNode(space)
  745. # protoStreet = self.generateProtoNode(street)
  746. # act = message.NewAction()
  747. # act.type = 2
  748. # act.wheelbase = wheelbase
  749. # act.spaceNode.CopyFrom(protoSpace)
  750. # act.streetNode.CopyFrom(protoStreet)
  751. #
  752. # actions.append(act)
  753. # if type == "nav":
  754. # act = self.CreateNavPathNodesAction(nodes, autoDirect)
  755. # if act is None:
  756. # print("Nav cmd is None")
  757. # return False
  758. # else:
  759. # actions.append(act)
  760. #
  761. # return actions
  762. def SetSequence(self, s_type: int):
  763. self.current_sequence_ = s_type
  764. def ResetSequence(self):
  765. self.current_sequence_ = 0