Connection_e1.py 28 KB

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