Connection_e1.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. """
  2. """
  3. from hub import methods, Global, protobuf
  4. from werkzeug.security import check_password_hash
  5. import struct
  6. import asyncio
  7. import time
  8. import socket
  9. clients = {} # {<ipv4>: (socket, update_at, type)} | {<连接id>: (socket对象, 最后一次请求时间, 客户端类型)}
  10. serial_rid_dict = {
  11. '65F7171A-5585-46C7-A9D6-967ABA9EB223': 1000000,
  12. '7AF3F619-5067-4EE0-A710-89A6CB097EFE': 1000001,
  13. 'ECB93A87-560B-4022-8C5F-CBF9FE1E596A': 1000002,
  14. 'C0D14B6F-0FF0-4B68-877D-D2CB886FCD0E': 1000002,
  15. 'E537DDFB-6E3E-4E1A-AD18-AC21393BE300': 1000004, # 正在使用
  16. }
  17. account_uid_dict = {
  18. 'ego': 3
  19. }
  20. # live_relationship = {} # {<id-1>id-2>: True}
  21. class SRIConnection(asyncio.Protocol):
  22. """"""
  23. head_sequence = '<hh' # 字节序规则
  24. head_size = struct.calcsize(head_sequence)
  25. message_data = b''
  26. def __init__(self):
  27. self.lock = asyncio.Lock() # 初始化锁
  28. def connection_made(self, client):
  29. """
  30. 建立客户端连接
  31. """
  32. peername = client.get_extra_info('peername')
  33. # self.connection_id = f"{peername[0].replace('.', '')}-{peername[1]}" # 客户端id
  34. # self.connection_id = int(f"{peername[1]}") # 客户端id(公网情况)
  35. self.connection_id = int(f"{peername[0].replace('.', '')}") # 客户端id(局域网情况)
  36. self.client = client
  37. # self.data = b''
  38. self.client_type = None
  39. self.client_info = None
  40. self.update_at = methods.now_ts()
  41. clients[self.connection_id] = self
  42. # 获取底层 socket
  43. # sock = self.client.get_extra_info('socket')
  44. # 查看缓冲区大小
  45. # recv_buffer_size = sock.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF)
  46. # send_buffer_size = sock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
  47. # methods.debug_log(f'{self.connection_id}|SRIConnection70', f"Receive buffer size: {recv_buffer_size}")
  48. # methods.debug_log(f'{self.connection_id}|SRIConnection70', f"Send buffer size: {send_buffer_size}")
  49. def connection_lost(self, exc):
  50. """
  51. 关闭连接
  52. """
  53. methods.debug_log(f"{self.connection_id}|SRIConnection|65", f"连接已关闭")
  54. methods.debug_log(f"{self.connection_id}|SRIConnection|65", f"clients: len{clients}")
  55. # --- 处理车端掉线,通知所有舱端
  56. if self.client_type == 'vehicle':
  57. """
  58. SCDelRobot: 消息体
  59. SCDelRobot.peer: int32
  60. SCDelRobot.egotype: int32
  61. """
  62. o2 = protobuf.SCDelRobot()
  63. o2.peer = self.client_info.get('connection_id') # 车端id
  64. o2.egotype = self.client_info.get('egotype')
  65. re_command_id = protobuf.SC_NotifyDel # 4017
  66. re_body_length = o2.ByteSize()
  67. re_head_data = struct.pack(self.head_sequence, re_command_id, re_body_length)
  68. re_body_data = o2.SerializeToString()
  69. re_send_data = re_head_data + re_body_data
  70. methods.debug_log(f"{self.connection_id}|SRIConnection085", f"re_command_id: {re_command_id}")
  71. for item in clients.values():
  72. if item.client_type == 'cockpit':
  73. item.client.write(re_send_data)
  74. # --- 处理舱端掉线,通知所有车端
  75. if self.client_type == 'cockpit':
  76. """
  77. Leave: 消息体
  78. Leave.peer: int32(车端rid)
  79. Leave.egotype: int32
  80. """
  81. o2 = protobuf.Leave()
  82. o2.peer = self.client_info.get('connection_id') # 舱端id
  83. o2.egotype = 1 # 客户端类型
  84. re_command_id = protobuf.SC_NotifyLeave # 4014
  85. re_body_length = o2.ByteSize()
  86. re_head_data = struct.pack(self.head_sequence, re_command_id, re_body_length)
  87. re_body_data = o2.SerializeToString()
  88. re_send_data = re_head_data + re_body_data
  89. methods.debug_log(f"{self.connection_id}|SRIConnection515", f"re_command_id: {re_command_id}")
  90. for item in clients.values():
  91. if item.client_type == 'vehicle':
  92. item.client.write(re_send_data)
  93. # --- clean
  94. if self.connection_id in clients:
  95. del clients[self.connection_id]
  96. # --- clean live_relationship
  97. # keys = [key for key in live_relationship.keys() if self.connection_id in key]
  98. # for key in keys:
  99. # del live_relationship[key]
  100. def data_received(self, data):
  101. """
  102. 消息处理
  103. """
  104. asyncio.create_task(self.handle_data(data))
  105. async def handle_data(self, data):
  106. """
  107. 消息处理
  108. """
  109. # --- before
  110. # loop = asyncio.get_running_loop()
  111. # await loop.run_in_executor(None, self.process_data, data)
  112. # async with self.lock: # 加入锁,确保只有一个任务在处理数据
  113. # await self.process_data(data)
  114. async with self.lock: # 加入锁,确保只有一个任务在处理数据
  115. loop = asyncio.get_running_loop()
  116. await loop.run_in_executor(None, self.process_data, data) # 调用非异步函数
  117. def process_data(self, data):
  118. """
  119. 消息处理
  120. """
  121. try:
  122. # methods.debug_log(f"{self.connection_id}|SRIConnection114", f"receive: {len(data)}, message: {repr(data)}")
  123. self.message_data += data # 执行了这个以后
  124. # methods.debug_log(f"{self.connection_id}|SRIConnection114", f"--- 1")
  125. # methods.debug_log(f"{self.connection_id}|SRIConnection114", f"--- 2")
  126. # methods.debug_log(f"{self.connection_id}|SRIConnection114", f"--- 3")
  127. # count = 0
  128. while True:
  129. # --- print
  130. # count += 1
  131. # methods.debug_log(f"{self.connection_id}|SRIConnection123",
  132. # f"---------------------------------- while count: {count}")
  133. # 确保有足够的字节来处理消息头
  134. if len(self.message_data) < self.head_size:
  135. break
  136. # 获取消息头
  137. head_data = self.message_data[:self.head_size]
  138. command_id, body_length = struct.unpack(self.head_sequence, head_data)
  139. if command_id not in [2008]:
  140. methods.debug_log(f'{self.connection_id}|SRIConnection.166',
  141. f"command_id: {command_id}, body_length: {body_length}")
  142. # else:
  143. # methods.debug_log(f'{self.connection_id}|SRIConnection.169',
  144. # f"command_id: {command_id}, body_length: {body_length}")
  145. # 检查命令ID是否有效
  146. if not (1000 < command_id < 9000):
  147. self.message_data = b'' # 清空无效数据
  148. break
  149. # 检查完整消息是否接收完毕
  150. total_length = self.head_size + body_length
  151. if len(self.message_data) < total_length:
  152. break # 数据不完整,等待更多数据
  153. # 调用相应处理方法
  154. method = getattr(self, f'message{command_id}', None)
  155. if method:
  156. method(self.message_data[self.head_size:total_length]) # 处理完整消息
  157. else:
  158. methods.debug_log(f"{self.connection_id}|SRIConnectionError",
  159. f"No handler for command_id: {command_id}")
  160. # 移除已处理的消息
  161. self.message_data = self.message_data[total_length:]
  162. except Exception as exception:
  163. methods.debug_log(f"{self.connection_id}|SRIConnection132", f"#exception: {exception}")
  164. methods.debug_log(f"{self.connection_id}|SRIConnection123", f"#traceback: {methods.trace_log()}")
  165. def message2008(self, body_data):
  166. # methods.debug_log(f"{self.connection_id}|SRIConnection80", f"message: 2008")
  167. pass
  168. def message2009(self, body_data):
  169. # --- 监听 2009
  170. """
  171. CSAdd: 消息体
  172. CSAdd.serial: string
  173. CSAdd.type: int32 EgoType::Car | 0 EgoType::None 1 EgoType::User 2 EgoType::Car
  174. CSAdd.name: string
  175. """
  176. object0 = protobuf.CSAdd()
  177. object0.ParseFromString(body_data)
  178. methods.debug_log(f"{self.connection_id}|SRIConnection219", f"#serial: {object0.serial}")
  179. # methods.debug_log(f"{self.connection_id}|SRIConnection90", f"#name: {object0.name}")
  180. # methods.debug_log(f"{self.connection_id}|SRIConnection90", f"#type: {object0.type}")
  181. # --- update ---
  182. self.client_type = 'vehicle'
  183. self.client_info = {
  184. 'connection_id': self.connection_id,
  185. 'rid': serial_rid_dict.get(object0.serial),
  186. 'name': object0.name,
  187. 'serial': object0.serial,
  188. 'egotype': 2, # 客户端类型
  189. }
  190. """
  191. SCAddRobot: 消息体
  192. SCAddRobot.robot: Robot
  193. Robot: 消息体
  194. Robot.rid: int32
  195. Robot.name: string
  196. Robot.type: int32
  197. Robot.state: RobotState Offline Online Busy
  198. """
  199. o1 = protobuf.Robot()
  200. # o1.rid = self.client_info.get('rid')
  201. o1.rid = self.client_info.get('connection_id')
  202. o1.name = object0.name
  203. o1.type = 2 # 0 EgoType::None 1 EgoType::User 2 EgoType::Car
  204. o1.state = protobuf.Robot.Online
  205. o2 = protobuf.SCAddRobot()
  206. o2.robot.CopyFrom(o1)
  207. re_command_id = protobuf.SC_NotifyAdd # 4016
  208. re_body_length = o2.ByteSize()
  209. re_head_data = struct.pack(self.head_sequence, re_command_id, re_body_length)
  210. re_body_data = o2.SerializeToString()
  211. re_send_data = re_head_data + re_body_data
  212. # --- send 4016 发送全部舱端
  213. for item in clients.values():
  214. if item.client_type == 'cockpit':
  215. methods.debug_log(f"{self.connection_id}|SRIConnection136", f"re_command_id: {re_command_id}")
  216. item.client.write(re_send_data)
  217. # --- send 4007 todo 凯强说并未用到
  218. # o1 = protobuf.SCAdd()
  219. # o1.ret = True
  220. # o1.uid = 112233 # todo 这个uid,应该是哪个舱端永辉在操作这个车 | 但是现在还没有人操控车
  221. # o1.name = object0.name
  222. # re_command_id = protobuf.SC_Add # 4007
  223. # re_body_length = o1.ByteSize()
  224. # re_head_data = struct.pack(self.head_sequence, re_command_id, re_body_length)
  225. # re_body_data = o1.SerializeToString()
  226. # re_send_data = re_head_data + re_body_data
  227. # methods.debug_log(f"{self.connection_id} | SRIConnection150", f"re_command_id: {re_command_id}")
  228. # self.client.write(re_send_data)
  229. def message2000(self, body_data):
  230. # --- 解析消息体 2000
  231. object = protobuf.CSSign()
  232. object.ParseFromString(body_data)
  233. methods.debug_log(f"{self.connection_id}|SRIConnection162", f"#account: {object.account}")
  234. methods.debug_log(f"{self.connection_id}|SRIConnection162", f"#password: {object.password}")
  235. # --- update ---
  236. ret = True
  237. if object.account == "Ego" and object.password != '123456':
  238. ret = False
  239. # --- check ---
  240. user = Global.mdb.get_one('UserInfo', {'username': object.account})
  241. name = ''
  242. uuid = ''
  243. if not user:
  244. ret = False
  245. elif not check_password_hash(user.get('password'), object.password):
  246. ret = False
  247. elif user.get('state') and int(user.get('state')) == 1:
  248. ret = False
  249. else:
  250. name = user.get('name')
  251. uuid = str(user.get('_id'))
  252. ret = True
  253. # --- update ---
  254. if ret:
  255. self.client_type = 'cockpit'
  256. self.client_info = {
  257. 'connection_id': self.connection_id,
  258. 'uid': 3, # 对应数据库里的ego的id
  259. 'name': object.account, # 对应数据库里
  260. 'egotype': 1, # 舱端类型
  261. 'user_uuid': uuid, # 用户id
  262. }
  263. # --- send 4000
  264. object = protobuf.SCSign()
  265. object.ret = ret # 返回结果
  266. object.uid = self.connection_id
  267. object.name = name # 人员名称
  268. object.user_uuid = uuid # 人员唯一标识
  269. re_command_id = protobuf.SC_Sign # 4000
  270. re_body_length = object.ByteSize()
  271. re_head_data = struct.pack(self.head_sequence, re_command_id, re_body_length)
  272. re_body_data = object.SerializeToString()
  273. re_send_data = re_head_data + re_body_data
  274. methods.debug_log(f"{self.connection_id}|SRIConnection175", f"re_command_id: {re_command_id}")
  275. self.client.write(re_send_data)
  276. def message2010(self, body_data):
  277. # --- send 4008 发送全部车端信息列表
  278. """
  279. Robot: 消息体
  280. Robot.rid: string
  281. Robot.name: string
  282. Robot.type: int32 EgoType::Car | EgoType::None EgoType::User EgoType::Car
  283. Robot.state: enum Offline Online Busy
  284. """
  285. # --- 获取全部在线车辆列表
  286. o2 = protobuf.SCRobot()
  287. for item in clients.values():
  288. if item.client_type and item.client_type == 'vehicle':
  289. o1 = protobuf.Robot()
  290. # o1.rid = item.client_info.get('rid')
  291. o1.rid = item.client_info.get('connection_id')
  292. o1.name = item.client_info.get('name')
  293. o1.type = 2 # EgoType::Car
  294. o1.state = protobuf.Robot.RobotState.Value('Online')
  295. o2.robot.add().CopyFrom(o1)
  296. re_command_id = protobuf.SC_Robot # 4008
  297. re_body_length = o2.ByteSize()
  298. re_head_data = struct.pack(self.head_sequence, re_command_id, re_body_length)
  299. re_body_data = o2.SerializeToString()
  300. re_send_data = re_head_data + re_body_data
  301. methods.debug_log(f"{self.connection_id}|SRIConnection306", f"re_command_id: {re_command_id}")
  302. self.client.write(re_send_data)
  303. def message2001(self, body_data):
  304. # --- 解析消息体
  305. """
  306. CSReq: 消息体
  307. CSReq.peer: int32(rid,车端唯一标识)
  308. CSReq.index: int32(相机位置,RenderPosition)
  309. CSReq.egotype: int32(终端类型,舱端/车端)
  310. """
  311. o1 = protobuf.CSReq()
  312. o1.ParseFromString(body_data)
  313. methods.debug_log(f"{self.connection_id}|SRIConnection299.message2001", f"#peer: {o1.peer}")
  314. methods.debug_log(f"{self.connection_id}|SRIConnection299.message2001", f"#index: {o1.index}")
  315. # methods.debug_log(f"{self.connection_id}|SRIConnection299.message2001", f"#uid: {self.client_info.get('uid')}")
  316. # methods.debug_log(f"{self.connection_id}|SRIConnection299.message2001", f"#rid: {self.client_info.get('rid')}")
  317. # --- send 4009 指定车端
  318. for item in clients.values():
  319. if item.client_info.get('connection_id') == o1.peer:
  320. """
  321. CSReq: 消息体
  322. CSReq.peer: int32(rid,车端唯一标识)
  323. CSReq.index: int32(相机位置,RenderPosition)
  324. CSReq.egotype: int32(终端类型,舱端/车端)
  325. """
  326. o2 = protobuf.CSReq()
  327. o2.peer = self.client_info.get('connection_id') # 舱端id
  328. o2.index = o1.index
  329. o2.egotype = o1.egotype
  330. re_command_id = protobuf.SC_NotifyReq # 4009
  331. re_body_length = o2.ByteSize()
  332. re_head_data = struct.pack(self.head_sequence, re_command_id, re_body_length)
  333. re_body_data = o2.SerializeToString()
  334. re_send_data = re_head_data + re_body_data
  335. methods.debug_log(f"{self.connection_id}|SRIConnection217", f"re_command_id: {re_command_id}")
  336. item.client.write(re_send_data)
  337. def message2002(self, body_data):
  338. # --- 解析消息体
  339. """
  340. CSRep: 消息体
  341. CSRep.desc: VideoDesc
  342. CSRep.peer: int32
  343. CSRep.index: int32
  344. CSRep.egotype: int32
  345. """
  346. o1 = protobuf.CSRep()
  347. o1.ParseFromString(body_data)
  348. methods.debug_log(f"{self.connection_id}|SRIConnection319", f"#peer: {o1.peer}")
  349. # methods.debug_log(f"{self.connection_id}|SRIConnection235", f"#uid: {self.client_info.get('uid')}")
  350. # methods.debug_log(f"{self.connection_id}|SRIConnection235", f"#rid: {self.client_info.get('rid')}")
  351. # --- send 4010 指定舱端
  352. for item in clients.values():
  353. if item.client_info.get('connection_id') == o1.peer:
  354. o2 = protobuf.CSRep()
  355. o2.desc = o1.desc
  356. o2.peer = self.client_info.get('connection_id') # 车端id
  357. o2.index = o1.index
  358. o2.egotype = o1.egotype
  359. re_command_id = protobuf.SC_NotifyRep # 4010
  360. re_body_length = o2.ByteSize()
  361. re_head_data = struct.pack(self.head_sequence, re_command_id, re_body_length)
  362. re_body_data = o2.SerializeToString()
  363. re_send_data = re_head_data + re_body_data
  364. methods.debug_log(f"{self.connection_id}|SRIConnection217", f"re_command_id: {re_command_id}")
  365. item.client.write(re_send_data)
  366. def message2004(self, body_data):
  367. # --- 解析消息体
  368. """
  369. Offer: 消息体
  370. Offer.index: int32
  371. Offer.peer: int32(车端rid)
  372. Offer.type: string
  373. Offer.sdp: string
  374. """
  375. object = protobuf.Offer()
  376. object.ParseFromString(body_data)
  377. methods.debug_log(f"{self.connection_id}|SRIConnection348", f"#peer: {object.peer}")
  378. # methods.debug_log(f"{self.connection_id}|SRIConnection348", f"#uid: {self.client_info.get('uid')}")
  379. # methods.debug_log(f"{self.connection_id}|SRIConnection348", f"#rid: {self.client_info.get('rid')}")
  380. # --- send 4012 指定车端
  381. for item in clients.values():
  382. if item.client_info.get('connection_id') == object.peer:
  383. o1 = protobuf.Offer()
  384. o1.index = object.index
  385. o1.peer = self.client_info.get('connection_id') # 舱端id
  386. o1.type = object.type
  387. o1.sdp = object.sdp
  388. re_command_id = protobuf.SC_NotifyOffer # 4012
  389. re_body_length = o1.ByteSize()
  390. re_head_data = struct.pack(self.head_sequence, re_command_id, re_body_length)
  391. re_body_data = o1.SerializeToString()
  392. re_send_data = re_head_data + re_body_data
  393. methods.debug_log(f"{self.connection_id}|SRIConnection341", f"re_command_id: {re_command_id}")
  394. item.client.write(re_send_data)
  395. def message2005(self, body_data):
  396. # --- 解析消息体
  397. """
  398. Answer: 消息体
  399. Answer.index: int32
  400. Answer.peer: int32(舱端uid)
  401. Answer.type: string
  402. Answer.sdp: string
  403. """
  404. object = protobuf.Answer()
  405. object.ParseFromString(body_data)
  406. methods.debug_log(f"{self.connection_id}|SRIConnection411", f"#peer: {object.peer}")
  407. # methods.debug_log(f"{self.connection_id}|SRIConnection411", f"#uid: {self.client_info.get('uid')}")
  408. # methods.debug_log(f"{self.connection_id}|SRIConnection411", f"#rid: {self.client_info.get('rid')}")
  409. # --- send 4011 指定舱端
  410. for item in clients.values():
  411. if item.client_info.get('connection_id') == object.peer:
  412. o1 = protobuf.Answer()
  413. o1.index = object.index
  414. o1.peer = self.client_info.get('connection_id') # 车端id
  415. o1.type = object.type
  416. o1.sdp = object.sdp
  417. re_command_id = protobuf.SC_NotifyAnswer # 4011
  418. re_body_length = o1.ByteSize()
  419. re_head_data = struct.pack(self.head_sequence, re_command_id, re_body_length)
  420. re_body_data = o1.SerializeToString()
  421. re_send_data = re_head_data + re_body_data
  422. methods.debug_log(f"{self.connection_id}|SRIConnection428", f"re_command_id: {re_command_id}")
  423. methods.debug_log(f"{self.connection_id}|SRIConnection428", f"#index: {o1.index}")
  424. item.client.write(re_send_data)
  425. def message2006(self, body_data):
  426. # --- 解析消息体
  427. """
  428. Candidate: 消息体
  429. Candidate.index: int32
  430. Candidate.peer: int32(车端rid)
  431. Candidate.type: string
  432. Candidate.candidate: string
  433. Candidate.sdpMLineIndex: int32
  434. Candidate.sdpMid: string
  435. Candidate.egotype: int32
  436. """
  437. object = protobuf.Candidate()
  438. object.ParseFromString(body_data)
  439. methods.debug_log(f"{self.connection_id}|SRIConnection413", f"#peer: {object.peer}")
  440. # methods.debug_log(f"{self.connection_id}|SRIConnection413", f"#uid: {self.client_info.get('uid')}")
  441. # methods.debug_log(f"{self.connection_id}|SRIConnection413", f"#rid: {self.client_info.get('rid')}")
  442. for item in clients.values():
  443. # --- send 4013 舱端到车端
  444. if item.client_info.get('connection_id') == object.peer:
  445. o1 = protobuf.Candidate()
  446. o1.index = object.index
  447. o1.peer = self.client_info.get('connection_id') # 舱端id,
  448. o1.type = object.type
  449. o1.candidate = object.candidate
  450. o1.sdpMLineIndex = object.sdpMLineIndex
  451. o1.sdpMid = object.sdpMid
  452. o1.egotype = object.egotype
  453. re_command_id = protobuf.SC_NotifyCandidate # 4013
  454. re_body_length = o1.ByteSize()
  455. re_head_data = struct.pack(self.head_sequence, re_command_id, re_body_length)
  456. re_body_data = o1.SerializeToString()
  457. re_send_data = re_head_data + re_body_data
  458. methods.debug_log(f"{self.connection_id}|SRIConnection409", f"re_command_id: {re_command_id}")
  459. item.client.write(re_send_data)
  460. # --- send 4013 车端到舱端
  461. if item.client_info.get('connection_id') == object.peer:
  462. o1 = protobuf.Candidate()
  463. o1.index = object.index
  464. o1.peer = self.client_info.get('connection_id') # 车端id,
  465. o1.type = object.type
  466. o1.candidate = object.candidate
  467. o1.sdpMLineIndex = object.sdpMLineIndex
  468. o1.sdpMid = object.sdpMid
  469. o1.egotype = object.egotype
  470. re_command_id = protobuf.SC_NotifyCandidate # 4013
  471. re_body_length = o1.ByteSize()
  472. re_head_data = struct.pack(self.head_sequence, re_command_id, re_body_length)
  473. re_body_data = o1.SerializeToString()
  474. re_send_data = re_head_data + re_body_data
  475. methods.debug_log(f"{self.connection_id}|SRIConnection426", f"re_command_id: {re_command_id}")
  476. # methods.debug_log(f"{self.connection_id}|SRIConnection426", f"#candidate.out: {o1.candidate}")
  477. item.client.write(re_send_data)
  478. def message2007(self, body_data):
  479. # --- 解析消息体 2007
  480. """
  481. Leave: 消息体
  482. Leave.peer: int32(车端rid)
  483. Leave.egotype: int32
  484. """
  485. o1 = protobuf.Leave()
  486. o1.ParseFromString(body_data)
  487. methods.debug_log(f"{self.connection_id}|SRIConnection497", f"#peer: {o1.peer}")
  488. # --- send 4009 指定车端
  489. for item in clients.values():
  490. if item.client_info.get('connection_id') == o1.peer:
  491. """
  492. Leave: 消息体
  493. Leave.peer: int32(车端rid)
  494. Leave.egotype: int32
  495. """
  496. o2 = protobuf.Leave()
  497. o2.peer = self.client_info.get('connection_id') # 舱端id
  498. o2.egotype = o1.egotype
  499. re_command_id = protobuf.SC_NotifyLeave # 4014
  500. re_body_length = o2.ByteSize()
  501. re_head_data = struct.pack(self.head_sequence, re_command_id, re_body_length)
  502. re_body_data = o2.SerializeToString()
  503. re_send_data = re_head_data + re_body_data
  504. methods.debug_log(f"{self.connection_id}|SRIConnection515", f"re_command_id: {re_command_id}")
  505. item.client.write(re_send_data)
  506. def message2014(self, body_data):
  507. # --- 解析消息体 2014
  508. """
  509. message CSState
  510. {
  511. UserState state=1;
  512. int32 uid=2;
  513. };
  514. """
  515. o1 = protobuf.CSState()
  516. o1.ParseFromString(body_data)
  517. methods.debug_log(f"{self.connection_id}|SRIConnection|572", f"#state: {o1.state}")
  518. methods.debug_log(f"{self.connection_id}|SRIConnection|572", f"#uid: {o1.uid}")
  519. # --- send 4016 发送全部舱端
  520. for item in clients.values():
  521. if item.client_type == 'cockpit':
  522. """
  523. message SCState
  524. {
  525. UserState state=1;
  526. int32 uid=2;
  527. };
  528. """
  529. o2 = protobuf.SCState()
  530. o2.state = o1.state
  531. o2.uid = o1.uid # 车端id
  532. re_command_id = protobuf.SC_State # 4022
  533. re_body_length = o2.ByteSize()
  534. re_head_data = struct.pack(self.head_sequence, re_command_id, re_body_length)
  535. re_body_data = o2.SerializeToString()
  536. re_send_data = re_head_data + re_body_data
  537. methods.debug_log(f"{self.connection_id}|SRIConnection551", f"re_command_id: {re_command_id}")
  538. item.client.write(re_send_data)
  539. # --- send 6011 指发送车端操作用户的id
  540. for item in clients.values():
  541. if item.client_info.get('connection_id') == o1.uid:
  542. """
  543. Leave: 消息体
  544. Leave.peer: int32(车端rid)
  545. Leave.egotype: int32
  546. """
  547. o3 = protobuf.UserActivityInfo()
  548. o3.user_uuid = self.client_info.get('user_uuid') # 用户uuid
  549. o3.cockpit_id = self.connection_id # 舱端id
  550. o3.vehicle_id = o1.uid # 车端id
  551. re_command_id = protobuf.S2V_SendUserInfo # 6011
  552. re_body_length = o3.ByteSize()
  553. re_head_data = struct.pack(self.head_sequence, re_command_id, re_body_length)
  554. re_body_data = o3.SerializeToString()
  555. re_send_data = re_head_data + re_body_data
  556. methods.debug_log(f"{self.connection_id}|SRIConnection611", f"re_command_id: {re_command_id}")
  557. item.client.write(re_send_data)
  558. @staticmethod
  559. async def check_clients():
  560. """
  561. 剔除掉线连接
  562. """
  563. count = 0
  564. while True:
  565. count += 1
  566. print(f"#count: {count}", flush=True)
  567. now_at = methods.now_ts()
  568. for connection_id in list(clients.keys()):
  569. object = clients.get(connection_id)
  570. print(f"#client: {object.client}, #update_at: {object.update_at}, #client_type: {object.client_type}",
  571. flush=True)
  572. await asyncio.sleep(3) # 发送消息的间隔时间
  573. @staticmethod
  574. async def run():
  575. """
  576. """
  577. # --- define ---
  578. loop = asyncio.get_running_loop()
  579. server = await loop.create_server(
  580. lambda: SRIConnection(),
  581. '0.0.0.0', Global.egoserver_port
  582. )
  583. # --- start ---
  584. async with server:
  585. print(f"Server listening on 0.0.0.0:{Global.egoserver_port}", flush=True)
  586. # await loop.create_task(SRIConnection.check_clients())
  587. await server.serve_forever()
  588. if __name__ == '__main__':
  589. asyncio.run(SRIConnection.run())