Connection_e1.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  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. object.user_uuid = str(user.get('_id')) # 人员唯一标识
  272. re_command_id = protobuf.SC_Sign # 4000
  273. re_body_length = object.ByteSize()
  274. re_head_data = struct.pack(self.head_sequence, re_command_id, re_body_length)
  275. re_body_data = object.SerializeToString()
  276. re_send_data = re_head_data + re_body_data
  277. methods.debug_log(f"{self.connection_id}|SRIConnection175", f"re_command_id: {re_command_id}")
  278. self.client.write(re_send_data)
  279. def message2010(self, body_data):
  280. # --- send 4008 发送全部车端信息列表
  281. """
  282. Robot: 消息体
  283. Robot.rid: string
  284. Robot.name: string
  285. Robot.type: int32 EgoType::Car | EgoType::None EgoType::User EgoType::Car
  286. Robot.state: enum Offline Online Busy
  287. """
  288. # --- 获取全部在线车辆列表
  289. o2 = protobuf.SCRobot()
  290. for item in clients.values():
  291. if item.client_type and item.client_type == 'vehicle':
  292. o1 = protobuf.Robot()
  293. # o1.rid = item.client_info.get('rid')
  294. o1.rid = item.client_info.get('connection_id')
  295. o1.name = item.client_info.get('name')
  296. o1.type = 2 # EgoType::Car
  297. o1.state = protobuf.Robot.RobotState.Value('Online')
  298. o2.robot.add().CopyFrom(o1)
  299. re_command_id = protobuf.SC_Robot # 4008
  300. re_body_length = o2.ByteSize()
  301. re_head_data = struct.pack(self.head_sequence, re_command_id, re_body_length)
  302. re_body_data = o2.SerializeToString()
  303. re_send_data = re_head_data + re_body_data
  304. methods.debug_log(f"{self.connection_id}|SRIConnection306", f"re_command_id: {re_command_id}")
  305. self.client.write(re_send_data)
  306. def message2001(self, body_data):
  307. # --- 解析消息体
  308. """
  309. CSReq: 消息体
  310. CSReq.peer: int32(rid,车端唯一标识)
  311. CSReq.index: int32(相机位置,RenderPosition)
  312. CSReq.egotype: int32(终端类型,舱端/车端)
  313. """
  314. o1 = protobuf.CSReq()
  315. o1.ParseFromString(body_data)
  316. methods.debug_log(f"{self.connection_id}|SRIConnection299.message2001", f"#peer: {o1.peer}")
  317. methods.debug_log(f"{self.connection_id}|SRIConnection299.message2001", f"#index: {o1.index}")
  318. # methods.debug_log(f"{self.connection_id}|SRIConnection299.message2001", f"#uid: {self.client_info.get('uid')}")
  319. # methods.debug_log(f"{self.connection_id}|SRIConnection299.message2001", f"#rid: {self.client_info.get('rid')}")
  320. # --- send 4009 指定车端
  321. for item in clients.values():
  322. if item.client_info.get('connection_id') == o1.peer:
  323. """
  324. CSReq: 消息体
  325. CSReq.peer: int32(rid,车端唯一标识)
  326. CSReq.index: int32(相机位置,RenderPosition)
  327. CSReq.egotype: int32(终端类型,舱端/车端)
  328. """
  329. o2 = protobuf.CSReq()
  330. o2.peer = self.client_info.get('connection_id') # 舱端id
  331. o2.index = o1.index
  332. o2.egotype = o1.egotype
  333. re_command_id = protobuf.SC_NotifyReq # 4009
  334. re_body_length = o2.ByteSize()
  335. re_head_data = struct.pack(self.head_sequence, re_command_id, re_body_length)
  336. re_body_data = o2.SerializeToString()
  337. re_send_data = re_head_data + re_body_data
  338. methods.debug_log(f"{self.connection_id}|SRIConnection217", f"re_command_id: {re_command_id}")
  339. item.client.write(re_send_data)
  340. def message2002(self, body_data):
  341. # --- 解析消息体
  342. """
  343. CSRep: 消息体
  344. CSRep.desc: VideoDesc
  345. CSRep.peer: int32
  346. CSRep.index: int32
  347. CSRep.egotype: int32
  348. """
  349. o1 = protobuf.CSRep()
  350. o1.ParseFromString(body_data)
  351. methods.debug_log(f"{self.connection_id}|SRIConnection319", f"#peer: {o1.peer}")
  352. # methods.debug_log(f"{self.connection_id}|SRIConnection235", f"#uid: {self.client_info.get('uid')}")
  353. # methods.debug_log(f"{self.connection_id}|SRIConnection235", f"#rid: {self.client_info.get('rid')}")
  354. # --- send 4010 指定舱端
  355. for item in clients.values():
  356. if item.client_info.get('connection_id') == o1.peer:
  357. o2 = protobuf.CSRep()
  358. o2.desc = o1.desc
  359. o2.peer = self.client_info.get('connection_id') # 车端id
  360. o2.index = o1.index
  361. o2.egotype = o1.egotype
  362. re_command_id = protobuf.SC_NotifyRep # 4010
  363. re_body_length = o2.ByteSize()
  364. re_head_data = struct.pack(self.head_sequence, re_command_id, re_body_length)
  365. re_body_data = o2.SerializeToString()
  366. re_send_data = re_head_data + re_body_data
  367. methods.debug_log(f"{self.connection_id}|SRIConnection217", f"re_command_id: {re_command_id}")
  368. item.client.write(re_send_data)
  369. def message2004(self, body_data):
  370. # --- 解析消息体
  371. """
  372. Offer: 消息体
  373. Offer.index: int32
  374. Offer.peer: int32(车端rid)
  375. Offer.type: string
  376. Offer.sdp: string
  377. """
  378. object = protobuf.Offer()
  379. object.ParseFromString(body_data)
  380. methods.debug_log(f"{self.connection_id}|SRIConnection348", f"#peer: {object.peer}")
  381. # methods.debug_log(f"{self.connection_id}|SRIConnection348", f"#uid: {self.client_info.get('uid')}")
  382. # methods.debug_log(f"{self.connection_id}|SRIConnection348", f"#rid: {self.client_info.get('rid')}")
  383. # --- send 4012 指定车端
  384. for item in clients.values():
  385. if item.client_info.get('connection_id') == object.peer:
  386. o1 = protobuf.Offer()
  387. o1.index = object.index
  388. o1.peer = self.client_info.get('connection_id') # 舱端id
  389. o1.type = object.type
  390. o1.sdp = object.sdp
  391. re_command_id = protobuf.SC_NotifyOffer # 4012
  392. re_body_length = o1.ByteSize()
  393. re_head_data = struct.pack(self.head_sequence, re_command_id, re_body_length)
  394. re_body_data = o1.SerializeToString()
  395. re_send_data = re_head_data + re_body_data
  396. methods.debug_log(f"{self.connection_id}|SRIConnection341", f"re_command_id: {re_command_id}")
  397. item.client.write(re_send_data)
  398. def message2005(self, body_data):
  399. # --- 解析消息体
  400. """
  401. Answer: 消息体
  402. Answer.index: int32
  403. Answer.peer: int32(舱端uid)
  404. Answer.type: string
  405. Answer.sdp: string
  406. """
  407. object = protobuf.Answer()
  408. object.ParseFromString(body_data)
  409. methods.debug_log(f"{self.connection_id}|SRIConnection411", f"#peer: {object.peer}")
  410. # methods.debug_log(f"{self.connection_id}|SRIConnection411", f"#uid: {self.client_info.get('uid')}")
  411. # methods.debug_log(f"{self.connection_id}|SRIConnection411", f"#rid: {self.client_info.get('rid')}")
  412. # --- send 4011 指定舱端
  413. for item in clients.values():
  414. if item.client_info.get('connection_id') == object.peer:
  415. o1 = protobuf.Answer()
  416. o1.index = object.index
  417. o1.peer = self.client_info.get('connection_id') # 车端id
  418. o1.type = object.type
  419. o1.sdp = object.sdp
  420. re_command_id = protobuf.SC_NotifyAnswer # 4011
  421. re_body_length = o1.ByteSize()
  422. re_head_data = struct.pack(self.head_sequence, re_command_id, re_body_length)
  423. re_body_data = o1.SerializeToString()
  424. re_send_data = re_head_data + re_body_data
  425. methods.debug_log(f"{self.connection_id}|SRIConnection428", f"re_command_id: {re_command_id}")
  426. methods.debug_log(f"{self.connection_id}|SRIConnection428", f"#index: {o1.index}")
  427. item.client.write(re_send_data)
  428. def message2006(self, body_data):
  429. # --- 解析消息体
  430. """
  431. Candidate: 消息体
  432. Candidate.index: int32
  433. Candidate.peer: int32(车端rid)
  434. Candidate.type: string
  435. Candidate.candidate: string
  436. Candidate.sdpMLineIndex: int32
  437. Candidate.sdpMid: string
  438. Candidate.egotype: int32
  439. """
  440. object = protobuf.Candidate()
  441. object.ParseFromString(body_data)
  442. methods.debug_log(f"{self.connection_id}|SRIConnection413", f"#peer: {object.peer}")
  443. # methods.debug_log(f"{self.connection_id}|SRIConnection413", f"#uid: {self.client_info.get('uid')}")
  444. # methods.debug_log(f"{self.connection_id}|SRIConnection413", f"#rid: {self.client_info.get('rid')}")
  445. for item in clients.values():
  446. # --- send 4013 舱端到车端
  447. if item.client_info.get('connection_id') == object.peer:
  448. o1 = protobuf.Candidate()
  449. o1.index = object.index
  450. o1.peer = self.client_info.get('connection_id') # 舱端id,
  451. o1.type = object.type
  452. o1.candidate = object.candidate
  453. o1.sdpMLineIndex = object.sdpMLineIndex
  454. o1.sdpMid = object.sdpMid
  455. o1.egotype = object.egotype
  456. re_command_id = protobuf.SC_NotifyCandidate # 4013
  457. re_body_length = o1.ByteSize()
  458. re_head_data = struct.pack(self.head_sequence, re_command_id, re_body_length)
  459. re_body_data = o1.SerializeToString()
  460. re_send_data = re_head_data + re_body_data
  461. methods.debug_log(f"{self.connection_id}|SRIConnection409", f"re_command_id: {re_command_id}")
  462. item.client.write(re_send_data)
  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}|SRIConnection426", f"re_command_id: {re_command_id}")
  479. # methods.debug_log(f"{self.connection_id}|SRIConnection426", f"#candidate.out: {o1.candidate}")
  480. item.client.write(re_send_data)
  481. def message2007(self, body_data):
  482. # --- 解析消息体
  483. """
  484. Leave: 消息体
  485. Leave.peer: int32(车端rid)
  486. Leave.egotype: int32
  487. """
  488. o1 = protobuf.Leave()
  489. o1.ParseFromString(body_data)
  490. methods.debug_log(f"{self.connection_id}|SRIConnection497", f"#peer: {o1.peer}")
  491. # --- send 4009 指定车端
  492. for item in clients.values():
  493. if item.client_info.get('connection_id') == o1.peer:
  494. """
  495. Leave: 消息体
  496. Leave.peer: int32(车端rid)
  497. Leave.egotype: int32
  498. """
  499. o2 = protobuf.Leave()
  500. o2.peer = self.client_info.get('connection_id') # 舱端id
  501. o2.egotype = o1.egotype
  502. re_command_id = protobuf.SC_NotifyLeave # 4014
  503. re_body_length = o2.ByteSize()
  504. re_head_data = struct.pack(self.head_sequence, re_command_id, re_body_length)
  505. re_body_data = o2.SerializeToString()
  506. re_send_data = re_head_data + re_body_data
  507. methods.debug_log(f"{self.connection_id}|SRIConnection515", f"re_command_id: {re_command_id}")
  508. item.client.write(re_send_data)
  509. def message2014(self, body_data):
  510. # --- 解析消息体
  511. """
  512. message CSState
  513. {
  514. UserState state=1;
  515. int32 uid=2;
  516. };
  517. """
  518. o1 = protobuf.CSState()
  519. o1.ParseFromString(body_data)
  520. methods.debug_log(f"{self.connection_id}|SRIConnection|572", f"#state: {o1.state}")
  521. methods.debug_log(f"{self.connection_id}|SRIConnection|572", f"#uid: {o1.uid}")
  522. # methods.debug_log(f"{self.connection_id}|SRIConnection|572", f"#uid: {o1.user_uuid}")
  523. # --- send 4016 发送全部舱端
  524. for item in clients.values():
  525. if item.client_type == 'cockpit':
  526. """
  527. message SCState
  528. {
  529. UserState state=1;
  530. int32 uid=2;
  531. };
  532. """
  533. o2 = protobuf.SCState()
  534. o2.state = o1.state
  535. o2.uid = o1.uid # 车端id
  536. re_command_id = protobuf.SC_State # 4022
  537. re_body_length = o2.ByteSize()
  538. re_head_data = struct.pack(self.head_sequence, re_command_id, re_body_length)
  539. re_body_data = o2.SerializeToString()
  540. re_send_data = re_head_data + re_body_data
  541. methods.debug_log(f"{self.connection_id}|SRIConnection551", f"re_command_id: {re_command_id}")
  542. item.client.write(re_send_data)
  543. # --- send 6011 指发送车端操作用户的id
  544. for item in clients.values():
  545. if item.client_info.get('connection_id') == o1.uid:
  546. """
  547. Leave: 消息体
  548. Leave.peer: int32(车端rid)
  549. Leave.egotype: int32
  550. """
  551. o3 = protobuf.UserActivityInfo()
  552. o3.user_uuid = 'SSGGSSEEFFHHWWSS' # 用户uuid
  553. # o3.user_uuid = o1.user_uuid # 用户uuid
  554. o3.cockpit_id = self.connection_id # 舱端id
  555. o3.vehicle_id = o1.uid # 车端id
  556. re_command_id = protobuf.S2V_SendUserInfo # 6011
  557. re_body_length = o3.ByteSize()
  558. re_head_data = struct.pack(self.head_sequence, re_command_id, re_body_length)
  559. re_body_data = o3.SerializeToString()
  560. re_send_data = re_head_data + re_body_data
  561. methods.debug_log(f"{self.connection_id}|SRIConnection611", f"re_command_id: {re_command_id}")
  562. item.client.write(re_send_data)
  563. @staticmethod
  564. async def check_clients():
  565. """
  566. 剔除掉线连接
  567. """
  568. count = 0
  569. while True:
  570. count += 1
  571. print(f"#count: {count}", flush=True)
  572. now_at = methods.now_ts()
  573. for connection_id in list(clients.keys()):
  574. object = clients.get(connection_id)
  575. print(f"#client: {object.client}, #update_at: {object.update_at}, #client_type: {object.client_type}",
  576. flush=True)
  577. await asyncio.sleep(3) # 发送消息的间隔时间
  578. @staticmethod
  579. async def run():
  580. """
  581. """
  582. # --- define ---
  583. loop = asyncio.get_running_loop()
  584. server = await loop.create_server(
  585. lambda: SRIConnection(),
  586. '0.0.0.0', 20917
  587. )
  588. # --- start ---
  589. async with server:
  590. print("Server listening on 0.0.0.0:20917", flush=True)
  591. # await loop.create_task(SRIConnection.check_clients())
  592. await server.serve_forever()
  593. if __name__ == '__main__':
  594. asyncio.run(SRIConnection.run())