RobotData.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  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 > 4:
  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. if len(self.currentNavPathNodes_)==1:
  234. self.currentNavPathNodes_.append(self.currentNavPathNodes_[0])
  235. actions = self.SplitPath(self.currentNavPathNodes_)
  236. for action in actions:
  237. [type, nodes] = action
  238. if type == "input":
  239. [street, space] = nodes
  240. protoSpace = self.generateProtoNode(space)
  241. protoStreet = self.generateProtoNode(street)
  242. act = message.NewAction()
  243. act.type = 1
  244. act.wheelbase = wheelbase
  245. act.spaceNode.CopyFrom(protoSpace)
  246. act.streetNode.CopyFrom(protoStreet)
  247. cmd.newActions.add().CopyFrom(act)
  248. if type == "output":
  249. [space, street] = nodes
  250. protoSpace = self.generateProtoNode(space)
  251. protoStreet = self.generateProtoNode(street)
  252. act = message.NewAction()
  253. act.type = 2
  254. act.wheelbase = wheelbase
  255. act.spaceNode.CopyFrom(protoSpace)
  256. act.streetNode.CopyFrom(protoStreet)
  257. cmd.newActions.add().CopyFrom(act)
  258. if type == "nav":
  259. action = self.CreateNavPathNodesAction(nodes, autoDirect)
  260. if action is None:
  261. print("Nav cmd is None")
  262. return False
  263. else:
  264. cmd.newActions.add().CopyFrom(action)
  265. print(cmd)
  266. if cmd is None:
  267. print("Nav cmd is None")
  268. return False
  269. channel = grpc.insecure_channel(self.rpc_ipport_)
  270. stub = msg_rpc.NavExcutorStub(channel)
  271. response = stub.Start(cmd)
  272. print("client received: ", response)
  273. if not response.ret == 0:
  274. print("nav failed :%s" % (response.info))
  275. return False
  276. else:
  277. print("nav completed !!!")
  278. return True
  279. def CreateNavPathNodesAction(self, path, autoDirect):
  280. # if path is not None and self.timedRobotStatu_.timeout() == False:
  281. if 1:
  282. for node in path:
  283. if isinstance(node, (SpaceNode)):
  284. print(" nodes must all street node")
  285. return None
  286. statu = self.timedRobotStatu_.statu
  287. # if statu is not None:
  288. if 1:
  289. newAction = message.NewAction()
  290. size = len(path)
  291. for i in range(size):
  292. node = path[i]
  293. pathNode = message.PathNode()
  294. pathNode.x = node.x_
  295. pathNode.y = node.y_
  296. pathNode.id = node.id_
  297. newAction.type = 4
  298. if autoDirect:
  299. newAction.type = 3
  300. newAction.pathNodes.add().CopyFrom(pathNode)
  301. return newAction
  302. else:
  303. print("statu is None")
  304. else:
  305. print("current path is none")
  306. return None
  307. def ExecPathNodes(self, autoDirect):
  308. if self.navCmdTopic_ == None:
  309. print("Robot has not set nav cmd topic")
  310. return False
  311. if not self.ActionType() == ActType.eReady:
  312. print(" robot is navigating ,key:%s" % (self.timedNavStatu_.statu.key))
  313. return False
  314. cmd = message.NavCmd()
  315. key = str(uuid.uuid4())
  316. cmd.key = key
  317. cmd.action = 0
  318. action = self.CreateNavPathNodesAction(self.currentNavPathNodes_, autoDirect)
  319. if action is None:
  320. print("Nav cmd is None")
  321. return False
  322. cmd.newActions.add().CopyFrom(action)
  323. print(cmd)
  324. channel = grpc.insecure_channel(self.rpc_ipport_)
  325. stub = msg_rpc.NavExcutorStub(channel)
  326. response = stub.Start(cmd)
  327. return True
  328. '''
  329. 根据AGV单车的起始位置调整路径
  330. '''
  331. def AdjustPath(self, path):
  332. adjusted_path = copy.deepcopy(path)
  333. y_offset = 1.2
  334. dy = 0
  335. # if self.IsMainAgv() or self.name_ == "AgvMain":
  336. if self.name_ == RobotName.strAGVMain:
  337. dy = 1
  338. # if not self.IsMainAgv() or self == "AGV2":
  339. if self.name_ == RobotName.strAGV2:
  340. dy = -1
  341. print("dy:", dy)
  342. for node in adjusted_path:
  343. if isinstance(node, StreetNode):
  344. if dy > 0:
  345. node.y_ += y_offset
  346. elif dy < 0:
  347. node.y_ -= y_offset
  348. else:
  349. pass
  350. return adjusted_path
  351. '''
  352. 拆分路径,生成动作集,input:入库动作,nav:导航动作,output:出库动作
  353. '''
  354. def SplitPath(self, path):
  355. space_count = 0
  356. for i in range(len(path)):
  357. if isinstance(path[i], (SpaceNode)):
  358. space_count += 1
  359. if i == 0 or i == len(path) - 1:
  360. pass
  361. else:
  362. print("Error: space node is not first/last of path")
  363. return None
  364. actions = []
  365. lastNode = None
  366. navIndex = -1
  367. for node in path:
  368. if lastNode == None:
  369. lastNode = node
  370. continue
  371. if isinstance(node, (SpaceNode)): # 当前点是车位点
  372. if isinstance(lastNode, (SpaceNode)): # 上一点为车位点
  373. print("Error: last node and current node is space node ")
  374. lastNode = None
  375. continue
  376. elif isinstance(lastNode, (StreetNode)): # 上一点为马路点,则动作为入库
  377. actions.append(["input", [lastNode, node]])
  378. lastNode = None
  379. continue
  380. if isinstance(node, (StreetNode)):
  381. if isinstance(lastNode, (SpaceNode)): # 上一点为车位点, 出库
  382. actions.append(["output", [lastNode, node]])
  383. elif isinstance(lastNode, (StreetNode)):
  384. if navIndex < 0:
  385. actions.append(["nav", [lastNode]])
  386. navIndex = len(actions) - 1
  387. actions[navIndex][1].append(node)
  388. lastNode = node
  389. return actions
  390. def SwitchMoveMode(self, mode, wheelbase):
  391. if self.IsMainAgv() == False:
  392. print(" this agv is single can not switch mode")
  393. return False
  394. cmd = message.NavCmd()
  395. key = str(uuid.uuid4())
  396. cmd.key = key
  397. cmd.action = 0
  398. action = message.NewAction()
  399. action.type = 8
  400. action.changedMode = mode
  401. if mode == 1:
  402. action.wheelbase = wheelbase
  403. cmd.newActions.add().CopyFrom(action)
  404. print(cmd)
  405. channel = grpc.insecure_channel(self.rpc_ipport_)
  406. stub = msg_rpc.NavExcutorStub(channel)
  407. response = stub.Start(cmd)
  408. return True
  409. def IsClampClosed(self):
  410. if self.timedRobotStatu_.timeout() == False:
  411. if self.IsMainModeStatu():
  412. clamp = self.timedRobotStatu_.statu.agvStatu.clamp
  413. clamp_other = self.timedRobotStatu_.statu.agvStatu.clamp_other
  414. return (clamp == 1 and clamp_other == 1)
  415. else:
  416. return self.timedRobotStatu_.statu.agvStatu.clamp == 1
  417. return False
  418. def IsClampRunning(self):
  419. if self.timedRobotStatu_.timeout() == False:
  420. if self.IsMainModeStatu():
  421. clamp = self.timedRobotStatu_.statu.agvStatu.clamp
  422. clamp_other = self.timedRobotStatu_.statu.agvStatu.clamp_other
  423. return (clamp == 0 or clamp_other == 0)
  424. else:
  425. return self.timedRobotStatu_.statu.agvStatu.clamp == 0
  426. return False
  427. def IsClampOpened(self):
  428. if self.timedRobotStatu_.timeout() == False:
  429. if self.IsMainModeStatu():
  430. clamp = self.timedRobotStatu_.statu.agvStatu.clamp
  431. clamp_other = self.timedRobotStatu_.statu.agvStatu.clamp_other
  432. return (clamp == 2 and clamp_other == 2)
  433. else:
  434. return self.timedRobotStatu_.statu.agvStatu.clamp == 2
  435. return False
  436. def ClampClose(self):
  437. if self.IsClampClosed() == True:
  438. print("clamp closed")
  439. return True
  440. cmd = message.NavCmd()
  441. cmd.action = 0
  442. key = str(uuid.uuid4())
  443. cmd.key = (key)
  444. act = message.NewAction()
  445. act.type = 6
  446. cmd.newActions.add().CopyFrom(act)
  447. channel = grpc.insecure_channel(self.rpc_ipport_)
  448. stub = msg_rpc.NavExcutorStub(channel)
  449. response = stub.Start(cmd)
  450. return True
  451. def ClampOpen(self):
  452. if self.IsClampOpened() == True:
  453. print("clamp opended")
  454. return True
  455. cmd = message.NavCmd()
  456. cmd.action = 0
  457. key = str(uuid.uuid4())
  458. cmd.key = (key)
  459. act = message.NewAction()
  460. act.type = 7
  461. cmd.newActions.add().CopyFrom(act)
  462. channel = grpc.insecure_channel(self.rpc_ipport_)
  463. stub = msg_rpc.NavExcutorStub(channel)
  464. response = stub.Start(cmd)
  465. return True
  466. def IsLiferDowned(self):
  467. if self.timedRobotStatu_.timeout() == False:
  468. if self.IsMainModeStatu():
  469. lifter = self.timedRobotStatu_.statu.agvStatu.lifter
  470. lifter_other = self.timedRobotStatu_.statu.agvStatu.lifter_other
  471. return (lifter == 2 and lifter_other == 2)
  472. else:
  473. return self.timedRobotStatu_.statu.agvStatu.lifter == 2
  474. return False
  475. def IsLiferRunning(self):
  476. if self.timedRobotStatu_.timeout() == False:
  477. if self.IsMainModeStatu():
  478. lifter = self.timedRobotStatu_.statu.agvStatu.lifter
  479. lifter_other = self.timedRobotStatu_.statu.agvStatu.lifter_other
  480. return (lifter == 0 and lifter_other == 0)
  481. else:
  482. return self.timedRobotStatu_.statu.agvStatu.lifter == 0
  483. return False
  484. def IsLiferRose(self):
  485. if self.timedRobotStatu_.timeout() == False:
  486. if self.IsMainModeStatu():
  487. lifter = self.timedRobotStatu_.statu.agvStatu.lifter
  488. lifter_other = self.timedRobotStatu_.statu.agvStatu.lifter_other
  489. return (lifter == 1 and lifter_other == 1)
  490. else:
  491. return self.timedRobotStatu_.statu.agvStatu.lifter == 1
  492. return False
  493. def LiferRise(self):
  494. if self.IsLiferRose() == True:
  495. print("lifter has rose")
  496. return True
  497. cmd = message.NavCmd()
  498. cmd.action = 0
  499. key = str(uuid.uuid4())
  500. cmd.key = (key)
  501. act = message.NewAction()
  502. act.type = 9
  503. cmd.newActions.add().CopyFrom(act)
  504. channel = grpc.insecure_channel(self.rpc_ipport_)
  505. stub = msg_rpc.NavExcutorStub(channel)
  506. response = stub.Start(cmd)
  507. return True
  508. def LiferDown(self):
  509. if self.IsLiferDowned() == True:
  510. print("lifter has downed")
  511. return True
  512. cmd = message.NavCmd()
  513. cmd.action = 0
  514. key = str(uuid.uuid4())
  515. cmd.key = (key)
  516. act = message.NewAction()
  517. act.type = 10
  518. cmd.newActions.add().CopyFrom(act)
  519. channel = grpc.insecure_channel(self.rpc_ipport_)
  520. stub = msg_rpc.NavExcutorStub(channel)
  521. response = stub.Start(cmd)
  522. return True
  523. def CancelNavTask(self):
  524. cmd = message.NavCmd()
  525. cmd.action = 3
  526. channel = grpc.insecure_channel(self.rpc_ipport_)
  527. stub = msg_rpc.NavExcutorStub(channel)
  528. response = stub.Cancel(cmd)
  529. print("client received: ", response)
  530. print(" Cancel task completed!!!")
  531. return True
  532. def IsManualTaskRunning(self):
  533. return self.manual_status != ManualOperationType.eReady
  534. def ManualTask(self, current_operation, step_acc=0, speed=0):
  535. if self.IsNavigating():
  536. print("AGV is navigating!!!")
  537. # return False
  538. # slowly stop
  539. if current_operation == ManualOperationType.eReady and \
  540. ManualOperationType.eReady < self.manual_status <= ManualOperationType.eRightMove:
  541. print("Manual_Unit_SlowlyStop")
  542. self.Manual_Unit_SlowlyStop(current_operation, speed)
  543. return True
  544. # if self.IsManualTaskRunning():
  545. # return print("ManualTask | ManualTask is running...")
  546. self.manual_status = current_operation
  547. if ManualOperationType.eReady < current_operation <= ManualOperationType.eRightMove:
  548. cmd = message.ToAgvCmd()
  549. self.heat_ += 1
  550. self.heat_ %= 255
  551. cmd.H1 = self.heat_
  552. if self.IsMainModeStatu():
  553. cmd.M1 = 1
  554. else:
  555. cmd.M1 = 0
  556. if current_operation == ManualOperationType.eCounterclockwiseRotate:
  557. cmd.T1 = 1
  558. cmd.V1 = 0
  559. cmd.W1 = speed / 180 * math.pi * sigmoid(step_acc, 0, 1)
  560. if current_operation == ManualOperationType.eClockwiseRotate:
  561. cmd.T1 = 1
  562. cmd.V1 = 0
  563. cmd.W1 = -speed / 180 * math.pi * sigmoid(step_acc, 0, 1)
  564. if current_operation == ManualOperationType.eForwardMove:
  565. cmd.T1 = 3
  566. cmd.V1 = speed * sigmoid(step_acc, 0, 1)
  567. cmd.W1 = 0
  568. if current_operation == ManualOperationType.eBackwardMove:
  569. cmd.T1 = 3
  570. cmd.V1 = -speed * sigmoid(step_acc, 0, 1)
  571. cmd.W1 = 0
  572. if current_operation == ManualOperationType.eLeftMove:
  573. cmd.T1 = 2
  574. cmd.V1 = speed * sigmoid(step_acc, 0, 1)
  575. cmd.W1 = 0
  576. if current_operation == ManualOperationType.eRightMove:
  577. cmd.T1 = 2
  578. cmd.V1 = -speed * sigmoid(step_acc, 0, 1)
  579. cmd.W1 = 0
  580. cmd.V2 = cmd.V1
  581. cmd.V3 = cmd.V1
  582. cmd.W2 = cmd.W1
  583. cmd.W3 = cmd.W1
  584. cmd.L1 = self.L_
  585. cmd.P1 = 0
  586. cmd.D1 = 0.0
  587. cmd.end = 1
  588. self.manual_speed = [cmd.V1, cmd.W1]
  589. # 处理为json格式
  590. cmd_dict = {}
  591. for field in cmd.DESCRIPTOR.fields:
  592. cmd_dict[field.name] = field.default_value
  593. for field, value in cmd.ListFields():
  594. cmd_dict[field.name] = value
  595. cmd_json = json.dumps(cmd_dict, indent=None, separators=(',', ':'))
  596. self.publish(self.speedCmdTopic, cmd_json)
  597. print(cmd_json)
  598. # channel = grpc.insecure_channel(self.rpc_ipport_)
  599. # stub = msg_rpc.NavExcutorStub(channel)
  600. # response = stub.ManualOperation(cmd_0)
  601. # print("client received: ", response)
  602. # self.manual_status = ManualOperationType.eReady
  603. # print("ManualOperation {op_type} task completed!!!".format(op_type=hex(current_operation)))
  604. time.sleep(0.05)
  605. return True
  606. elif ManualOperationType.eClampClose <= current_operation <= ManualOperationType.eClampOpen:
  607. self.Manual_Unit_Clamp(current_operation)
  608. return True
  609. elif ManualOperationType.eLifterRise <= current_operation <= ManualOperationType.eLifterDown:
  610. self.Manual_Unit_Lifter(current_operation)
  611. return True
  612. return False
  613. def Manual_Unit_Lifter(self, current_operation: ManualOperationType):
  614. print(current_operation)
  615. cmd = message.ToAgvCmd()
  616. self.heat_ += 1
  617. self.heat_ %= 255
  618. cmd.H1 = self.heat_
  619. if self.IsMainModeStatu():
  620. cmd.M1 = 1
  621. else:
  622. cmd.M1 = 0
  623. cmd.T1 = self.ManualOperationType2AgvCmdType(current_operation)
  624. # 处理为json格式 # jtf.MessageToJson(cmd)
  625. cmd_dict = {}
  626. for field in cmd.DESCRIPTOR.fields:
  627. cmd_dict[field.name] = field.default_value
  628. for field, value in cmd.ListFields():
  629. cmd_dict[field.name] = value
  630. cmd_json = json.dumps(cmd_dict, indent=None, separators=(',', ':'))
  631. self.publish(self.speedCmdTopic, cmd_json)
  632. print(cmd_json)
  633. # self.manual_status = ManualOperationType.eReady
  634. return True
  635. def Manual_Unit_Clamp(self, current_operation: ManualOperationType):
  636. print(current_operation)
  637. cmd = message.ToAgvCmd()
  638. self.heat_ += 1
  639. self.heat_ %= 255
  640. cmd.H1 = self.heat_
  641. if self.IsMainModeStatu():
  642. cmd.M1 = 1
  643. else:
  644. cmd.M1 = 0
  645. cmd.T1 = self.ManualOperationType2AgvCmdType(current_operation)
  646. # 处理为json格式 # jtf.MessageToJson(cmd)
  647. cmd_dict = {}
  648. for field in cmd.DESCRIPTOR.fields:
  649. cmd_dict[field.name] = field.default_value
  650. for field, value in cmd.ListFields():
  651. cmd_dict[field.name] = value
  652. cmd_json = json.dumps(cmd_dict, indent=None, separators=(',', ':'))
  653. self.publish(self.speedCmdTopic, cmd_json)
  654. print(cmd_json)
  655. # self.manual_status = ManualOperationType.eReady
  656. return True
  657. def ManualOperationType2AgvCmdType(self, mo_type: ManualOperationType):
  658. if mo_type == ManualOperationType.eLifterRise:
  659. return ActType.eLifterRise
  660. if mo_type == ManualOperationType.eLifterDown:
  661. return ActType.eLifterDown
  662. if mo_type == ManualOperationType.eClampClose:
  663. return ActType.eClampClose
  664. if mo_type == ManualOperationType.eClampOpen:
  665. return ActType.eClampOpen
  666. def Manual_Unit_SlowlyStop(self, current_operation: ManualOperationType, speed):
  667. step_sum = 10
  668. step_acc = 1
  669. speed_v = max(fabs(self.manual_speed[0]), 0.01)
  670. speed_w = max(fabs(self.manual_speed[1]), 1)
  671. while step_acc <= step_sum:
  672. if ManualOperationType.eReady < self.manual_status <= ManualOperationType.eRightMove:
  673. cmd = message.ToAgvCmd()
  674. self.heat_ += 1
  675. self.heat_ %= 255
  676. cmd.H1 = self.heat_
  677. if self.IsMainModeStatu():
  678. cmd.M1 = 1
  679. else:
  680. cmd.M1 = 0
  681. if self.manual_status == ManualOperationType.eCounterclockwiseRotate:
  682. cmd.T1 = 1
  683. cmd.V1 = 0
  684. cmd.W1 = speed_w / 180 * math.pi * (step_sum - step_acc) / step_sum
  685. if self.manual_status == ManualOperationType.eClockwiseRotate:
  686. cmd.T1 = 1
  687. cmd.V1 = 0
  688. cmd.W1 = -speed_w / 180 * math.pi * (step_sum - step_acc) / step_sum
  689. if self.manual_status == ManualOperationType.eForwardMove:
  690. cmd.T1 = 3
  691. cmd.V1 = speed_v * (step_sum - step_acc) / step_sum
  692. cmd.W1 = 0
  693. if self.manual_status == ManualOperationType.eBackwardMove:
  694. cmd.T1 = 3
  695. cmd.V1 = -speed_v * (step_sum - step_acc) / step_sum
  696. cmd.W1 = 0
  697. if self.manual_status == ManualOperationType.eLeftMove:
  698. cmd.T1 = 2
  699. cmd.V1 = speed_v * (step_sum - step_acc) / step_sum
  700. cmd.W1 = 0
  701. if self.manual_status == ManualOperationType.eRightMove:
  702. cmd.T1 = 2
  703. cmd.V1 = -speed_v * (step_sum - step_acc) / step_sum
  704. cmd.W1 = 0
  705. cmd.V2 = cmd.V1
  706. cmd.V3 = cmd.V1
  707. cmd.W2 = cmd.W1
  708. cmd.W3 = cmd.W1
  709. cmd.L1 = self.L_
  710. cmd.end = 1
  711. # 处理为json格式
  712. cmd_dict = {}
  713. for field in cmd.DESCRIPTOR.fields:
  714. cmd_dict[field.name] = field.default_value
  715. for field, value in cmd.ListFields():
  716. cmd_dict[field.name] = value
  717. cmd_json = json.dumps(cmd_dict, indent=None, separators=(',', ':'))
  718. self.publish(self.speedCmdTopic, cmd_json)
  719. print(cmd_json)
  720. step_acc += 1
  721. time.sleep(0.1)
  722. self.manual_status = ManualOperationType.eReady
  723. self.manual_speed = [0, 0]
  724. print("Manual_Unit_SlowlyStop completed.")
  725. return True
  726. # def GenerateActionMPC(self, beg_name, end_name, autoDirect, wheelbase=0, task_type="None"):
  727. # self.GeneratePath(beg_name, end_name)
  728. # actions = list()
  729. #
  730. # split_path = self.SplitPath(self.currentNavPathNodes_)
  731. # for action in split_path:
  732. # [type, nodes] = action
  733. # if type == "input":
  734. # [street, space] = nodes
  735. # protoSpace = self.generateProtoNode(space)
  736. # protoStreet = self.generateProtoNode(street)
  737. # act = message.NewAction()
  738. # act.type = 1
  739. # act.wheelbase = wheelbase
  740. # act.spaceNode.CopyFrom(protoSpace)
  741. # act.streetNode.CopyFrom(protoStreet)
  742. #
  743. # actions.append(act)
  744. # if type == "output":
  745. # [space, street] = nodes
  746. # protoSpace = self.generateProtoNode(space)
  747. # protoStreet = self.generateProtoNode(street)
  748. # act = message.NewAction()
  749. # act.type = 2
  750. # act.wheelbase = wheelbase
  751. # act.spaceNode.CopyFrom(protoSpace)
  752. # act.streetNode.CopyFrom(protoStreet)
  753. #
  754. # actions.append(act)
  755. # if type == "nav":
  756. # act = self.CreateNavPathNodesAction(nodes, autoDirect)
  757. # if act is None:
  758. # print("Nav cmd is None")
  759. # return False
  760. # else:
  761. # actions.append(act)
  762. #
  763. # return actions
  764. def SetSequence(self, s_type: int):
  765. self.current_sequence_ = s_type
  766. def ResetSequence(self):
  767. self.current_sequence_ = 0