Connection_e1.py 27 KB

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