RobotData.py 30 KB

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