Connection_e1.py 29 KB

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