Browse Source

Merge branch 'ZJZGJ' of http://www.sri-robot.cn:30000/SRI-DINO/Server-py into ZJZGJ

casper 2 months ago
parent
commit
58a7caa6ec

+ 3 - 1
sri-pysdk/xlib/xlog.py

@@ -18,7 +18,9 @@ def debug_log(tags, args, is_work=True, show_level=logging.INFO):
             lines += f"\n- {count + 1} - {line}"
         LOG.info(lines)
     elif type(args) == str:
-        LOG.info(f"{tags} | {args}")
+        now_string = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
+        LOG.info(f"{now_string} | {tags} | {args}")
+        # LOG.info(f"{tags} | {args}")
 
 
 def trace_log():

+ 19 - 2
sri-server-bg01/api/v6/code2000.py

@@ -54,6 +54,11 @@ async def code2002(**sources):
     elif not sources.get('size'):
         return dict(code=2, details=f"something is wrong.")
 
+    # --- get VehicleStatus ---
+    unique_dict = {'name': 'VehicleStatus'}
+    item = Global.mdb.get_one('GlobalVariable', unique_dict)
+    status_dict = item.get('args', {})
+
     # --- fill d1 ---
     d1 = list()
     page = sources.get('page', 1)
@@ -72,9 +77,17 @@ async def code2002(**sources):
             'rtk_address': item.get('rtk_address'),
             'cpe_address': item.get('cpe_address'),
             'release_at': item.get('release_at'),
-            'state': item.get('state', 1),
+            'state': item.get('state', 1),  # 1:离线 2:在线(空闲) 3: 现场驾驶中 4: 远程驾驶中
             'permit_state': item.get('permit_state', 0),
         }
+
+        # --- update state ---
+        vehicle_id = str(f"{item.get('host_address').replace('.', '')}")
+        if not status_dict.get(vehicle_id):
+            data['state'] = 1
+        else:
+            data['state'] = status_dict.get(vehicle_id)
+
         d1.append(data)
     return dict(code=0, data=d1[(page - 1) * size: page * size], total=len(d1), page=page, size=size)
 
@@ -128,6 +141,7 @@ async def code2003(**sources):
     Global.mdb.update_one_by_id('VehicleInfo', uuid, update_dict)
     return dict(code=0, data=uuid)
 
+
 async def code2004(**sources):
     """
     禁止指定车辆远程操作
@@ -160,6 +174,7 @@ async def code2004(**sources):
     item = Global.mdb.update_one_by_id('VehicleInfo', uuid, update_dict, need_back=True)
     return dict(code=0, data=item)
 
+
 async def code2005(**sources):
     """
     允许指定车辆远程操作
@@ -192,6 +207,7 @@ async def code2005(**sources):
     item = Global.mdb.update_one_by_id('VehicleInfo', uuid, update_dict, need_back=True)
     return dict(code=0, data=item)
 
+
 async def code2006(**sources):
     """
     删除指定车辆
@@ -210,6 +226,7 @@ async def code2006(**sources):
     Global.mdb.remove_one_by_id('VehicleInfo', uuid)
     return dict(code=0, data=uuid)
 
+
 async def code2007(**sources):
     """
     获取指定作业车辆详情
@@ -237,4 +254,4 @@ async def code2007(**sources):
     """
     item.pop('_id')
     item['uuid'] = uuid
-    return dict(code=0, data=item)
+    return dict(code=0, data=item)

+ 4 - 3
sri-server-bg01/api/v6/code3000.py

@@ -2,7 +2,7 @@ from hub import methods, Global
 
 import os
 
-save_dir = r'C:\logs'  # sri内网测试环境
+# save_dir = r'C:\logs'  # sri内网测试环境
 
 
 async def code3001(**sources):
@@ -16,9 +16,10 @@ async def code3001(**sources):
         return dict(code=2, details=f"something is wrong.")
 
     # --- get log_file_uuid_list ---
-    log_file_list = methods.get_file_path_list(save_dir)
+    log_file_list = methods.get_file_path_list(Global.save_dir)
     log_file_name_list = [i.split('\\')[-1] for i in log_file_list]
     log_file_uuid_list = [i.split('.')[0] for i in log_file_name_list]
+    methods.debug_log('code3000.22:', f"#log_file_uuid_list: {log_file_uuid_list}")
 
     # --- fill d2 ---
     d2 = dict()
@@ -103,7 +104,7 @@ async def code3002(**sources):
     # --- get file_path ---
     # log_uuid = '671754598302fc6fd344819f'
     log_uuid = sources.get('uuid')
-    file_path = os.path.join(save_dir, f"{log_uuid}.log")
+    file_path = os.path.join(Global.save_dir, f"{log_uuid}.log")
 
     # --- get file_name ---
     methods.debug_log('code3000.code3002|145:', f"#log_uuid: {log_uuid}")

+ 6 - 19
sri-server-bg01/hub.py

@@ -6,28 +6,15 @@ sys.path.append('../sri-pysdk')
 methods = importlib.import_module(f"xlib")
 
 
-# camera_handle = importlib.import_module(f"libraries.base_external.camera_by_cv2")
-# numpy_method = importlib.import_module(f"libraries.base_external.data_by_numpy")
-
-
 class Global(object):
-    # --- 时序数据库 ---
-    # xdb = importlib.import_module(f"clients.db_influx").Client(host='fra-middleware-influx', port=8086,
-    #                                                            database='vms')
 
-    # --- 业务数据数据库 ---
-    mdb = importlib.import_module(f"xclient.xmongo").Client(host='127.0.0.1', port=47017, database='bg',
-                                                            username='admin', password='admin')
-    # mdb = importlib.import_module(f"xclient.xmongo").Client(host='10.10.10.73', port=47017, database='bg',
-    #                                                         username='admin', password='admin')
-    # mysql = importlib.import_module(f"xclient.db_maria2").Client(host='58.34.94.176', port=8806, database='hs',
-    #                                                              username='root', password='rootroot&123123')
+    # --- 公司内网测试服务器 ---
+    # save_dir = r'C:\logs'  # sri内网测试环境
 
-    # --- 缓存数据库 ---
-    # rdb = importlib.import_module(f"clients.db_redis").Client(db=0, host='fra-middleware-redis', port=6379)
 
-    # SSHClient = importlib.import_module(f"clients.l4_ssh_by_paramiko").Client
+    # --- 湛江现场 ----
+    save_dir = r'E:\logs'  # 容量为512G
 
-    # local_api = importlib.import_module(f"apis.local.api").Api()
 
-    # mccbts_agent = importlib.import_module(f"xapi.mccbts.api").API()
+    mdb = importlib.import_module(f"xclient.xmongo").Client(host='127.0.0.1', port=47017, database='bg',
+                                                            username='admin', password='admin')

+ 1 - 1
sri-server-bg01/test/test-1000.py

@@ -124,7 +124,7 @@ print(response.json())
 # data = {
 #     'code': 1007,  # 接口号
 #     'uuid': '65dd775c44b74ae33732d7f7',  # 用户id(必须项)
-#     # 'username': 'aabbcc',  # 登录账户(必须项)
+#     # 'username': 'aabbcc',  # 登录账户(可选项)
 #     # 'password': 'aabbcc',  # 登录密码(可选项)(默认值:baosteel@2024)
 #     # 'role_type': 3,  # 角色类型(可选项)(1: 超级管理员 2: 普通管理员 3: 普通用户)
 #     'name': 'aabbcc',  # 姓名(可选项)

+ 11 - 10
sri-server-bg01/test/test-3000.py

@@ -2,8 +2,8 @@ import requests
 
 # --- test 获取token ---
 # url = 'http://58.34.94.177:29101/v1/token'
-# url = 'http://127.0.0.1:9000/v1/token'
-url = 'http://10.10.60.237:9000/v1/token'
+# url = 'http://10.10.60.237:9000/v1/token'
+url = 'http://127.0.0.1:9000/v1/token'
 data = {
     'username': 'admin',  # 用户名
     'password': '123456',  # 密码
@@ -15,7 +15,8 @@ token = response.headers.get('authorization')
 
 # --- test 3001 查询驾驶人员操作记录列表 ---
 # url = 'http://58.34.94.177:29101/v6/api'
-url = 'http://10.10.60.237:9000/v6/api'
+# url = 'http://10.10.60.237:9000/v6/api'
+url = 'http://127.0.0.1:9000/v6/api'
 data = {
     'code': 3001,  # 接口号
     'page': 1,  # 页码
@@ -45,10 +46,10 @@ print(response.json())
 """
 
 # --- test 3002 下载指定驾驶人员操作日志 ---
-url = 'http://58.34.94.177:29101/v6/api'
-params = {
-    'code': 3002,
-    'uuid': '65dbe96949fbe311a3a01d30',
-}
-response = requests.get(url=url, params=params, headers={'authorization': token})
-print(response.text)
+# url = 'http://58.34.94.177:29101/v6/api'
+# params = {
+#     'code': 3002,  # 接口号
+#     'uuid': '65dbe96949fbe311a3a01d30',  # 日志id
+# }
+# response = requests.get(url=url, params=params, headers={'authorization': token})
+# print(response.text)

+ 9 - 13
sri-server-bg02/hub.py

@@ -10,13 +10,17 @@ class Global(object):
     """
     """
 
-    save_dir = r'C:\logs'  # sri内网测试环境
-    # save_dir = r'E:\logs'  # 湛江现场环境(容量为512G)
-
-    # --- 中间件服务器 ---
+    # --- 公司内网测试服务器 ---
+    # save_dir = r'C:\logs'  # sri内网测试环境
+    # emqx_factory = importlib.import_module(f"xclient.xmqtt")
+    # emqx_host = '127.0.0.1'
+    # emqx_port = 41883
+
+    # --- 湛江现场 ----
+    save_dir = r'E:\logs'  # 容量为512G
     emqx_factory = importlib.import_module(f"xclient.xmqtt")
     emqx_host = '127.0.0.1'
-    emqx_port = 41883
+    emqx_port = 41881
 
     # --- 定时执行组件 ---
     aps = importlib.import_module(f"xpip.xapscheduler").APS(db_type='mongo',
@@ -28,11 +32,3 @@ class Global(object):
     # --- 业务数据数据库 ---
     mdb = importlib.import_module(f"xclient.xmongo").Client(host='127.0.0.1', port=47017, database='bg',
                                                             username='admin', password='admin')
-
-    # emqx = importlib.import_module(f"xclient.xmqtt").Client(host='10.10.10.73', port=41883)
-
-    # aps = importlib.import_module(f"xpip.xapscheduler").APS(db_type='mongo',
-    #                                                         db_host='10.10.10.73',
-    #                                                         db_port=47017,
-    #                                                         username='admin', password='admin',
-    #                                                         database='bg', collection='LoopTask')

+ 6 - 1
sri-server-bg02/lib/MessageListener.py

@@ -7,7 +7,6 @@ import json
 import os
 
 
-
 class MessageListener:
     """
     """
@@ -29,6 +28,9 @@ class MessageListener:
         v4 = TopicListener('Vehicle/ControlVehicle/Veh0537', 'method_v001')
         v5 = TopicListener('Vehicle/ControlVehicle/Veh0538', 'method_v001')
 
+        c1 = TopicListener('Cockpit/CanBus/CanId001/Cop001', 'method_c001')
+        c2 = TopicListener('Cockpit/CanBus/CanId001/Cop002', 'method_c001')
+
         thread_list = [
             threading.Thread(target=t1.subscribe),
             threading.Thread(target=t2.subscribe),
@@ -39,6 +41,9 @@ class MessageListener:
             threading.Thread(target=v4.subscribe),
             threading.Thread(target=v5.subscribe),
 
+            threading.Thread(target=c1.subscribe),
+            threading.Thread(target=c2.subscribe),
+
         ]
         for thread in thread_list:
             thread.setDaemon(True)

+ 23 - 21
sri-server-bg02/lib/TopicListener.py

@@ -13,10 +13,14 @@ from lib.UserWorkRecord import UserWorkRecord
 
 topic_info_dict = {}  # {<topic_name>: <last_log_key>}
 
+
 def method_v001(_client, _userdata, message):
     """消息处理方法"""
+    # --- get ---
+    topic = _client.casper_info.get('topic')
+
     # --- debug ---
-    # methods.debug_log(f"TopicListener|17", f"#message.payload: {message.payload}")
+    # methods.debug_log(f"TopicListener|{topic}|23", f"#message.payload: {message.payload}")
     # return
 
     # --- check ---
@@ -32,15 +36,15 @@ def method_v001(_client, _userdata, message):
         vehicle_id = log_dict.get('VehicleID')
         cockpit_id = log_dict.get('cockpitID')
     except Exception as exception:
-        methods.debug_log("TopicListener|35", f"#message.payload: {message.payload}")
-        methods.debug_log("TopicListener|35", f"#exception: {exception.__class__.__name__}")
-        methods.debug_log("TopicListener|35", f"#traceback: {traceback.format_exc()}")
+        methods.debug_log(f"TopicListener|{topic}|39", f"#message.payload: {message.payload}")
+        methods.debug_log(f"TopicListener|{topic}|39", f"#exception: {exception.__class__.__name__}")
+        methods.debug_log(f"TopicListener|{topic}|39", f"#traceback: {traceback.format_exc()}")
         return
 
     # --- check ---
     log_uuid = UserWorkRecord.get_log_uuid(user_uuid, log_time, vehicle_id, cockpit_id)
     if not log_uuid:
-        methods.debug_log(f"TopicListener|error50", f"user_uuid: {user_uuid}, log_time: {log_time}")
+        methods.debug_log(f"TopicListener|{topic}|39", f"user_uuid: {user_uuid}, log_time: {log_time}")
         return
 
     # --- fill log_list ---
@@ -66,7 +70,7 @@ def method_v001(_client, _userdata, message):
         f"accPedalF: {log_dict.get('driveControl')[0].get('accPedal')[0].get('accPedalF')}",  # 油门踏板.手油门
         f"accPedalH: {log_dict.get('driveControl')[0].get('accPedal')[0].get('accPedalH')}",  # 油门踏板.脚油门
 
-        f"accPedalH: {log_dict.get('driveControl')[0].get('brakePedal')}",  # 刹车踏板
+        f"brakePedal: {log_dict.get('driveControl')[0].get('brakePedal')}",  # 刹车踏板
         f"steeringWheel: {log_dict.get('driveControl')[0].get('steeringWheel')}",  # 方向盘转速
         f"turnMode: {log_dict.get('driveControl')[0].get('turnMode')}",  # 转向模式
         f"turnSignal: {log_dict.get('driveControl')[0].get('turnSignal')}",  # 转向灯
@@ -97,7 +101,6 @@ def method_v001(_client, _userdata, message):
     ]
 
     # --- get ---
-    topic = _client.casper_info.get('topic')
     last_log_key = topic_info_dict.get(topic)
 
     # --- check ---
@@ -110,13 +113,11 @@ def method_v001(_client, _userdata, message):
     topic_info_dict[topic] = log_key
 
     # --- save ---
-    # methods.debug_log(f"TopicListener|113", f"#log_list: {log_list}")
+    # methods.debug_log(f"TopicListener|{topic}|116", f"#log_list: {log_list}")
     log_file_path = os.path.join(Global.save_dir, f'{log_uuid}.log')
     methods.write_text(log_file_path, ' | '.join(log_list) + '\n', 'a')
 
 
-
-
 def method_c001(_client, _userdata, message):
     """消息处理方法"""
     """
@@ -171,19 +172,22 @@ def method_c001(_client, _userdata, message):
         'vehicleID': '0538'
     }
     """
+    # --- get ---
+    topic = _client.casper_info.get('topic')
+
     # --- debug ---
     # methods.debug_log(f"TopicListener|168", f"#_client: {_client.casper_info} | {type(_client.casper_info)}")
     # methods.debug_log(f"TopicListener|168", f"#_client: {_userdata} | {type(_userdata)}")
-    # methods.debug_log(f"TopicListener|168", f"#message.payload: {message.payload}")
+    # methods.debug_log(f"TopicListener|{topic}|179", f"#message.payload: {message.payload}")
     # return
 
     # --- check ---
     try:
         log_dict = json.loads(message.payload)
     except Exception as exception:
-        methods.debug_log("TopicListener|79", f"#message.payload: {message.payload}")
-        methods.debug_log("TopicListener|79", f"#exception: {exception.__class__.__name__}")
-        methods.debug_log("TopicListener|79", f"#traceback: {traceback.format_exc()}")
+        methods.debug_log(f"TopicListener|{topic}|186", f"#message.payload: {message.payload}")
+        methods.debug_log(f"TopicListener|{topic}|186", f"#exception: {exception.__class__.__name__}")
+        methods.debug_log(f"TopicListener|{topic}|186", f"#traceback: {traceback.format_exc()}")
         return
 
     # --- check ---
@@ -194,7 +198,7 @@ def method_c001(_client, _userdata, message):
     cockpit_id = log_dict.get('cockpitID')
     log_uuid = UserWorkRecord.get_log_uuid(user_uuid, log_time, vehicle_id, cockpit_id)
     if not log_uuid:
-        methods.debug_log(f"TopicListener|error92", f"user_uuid: {user_uuid}, log_time: {log_time}")
+        methods.debug_log(f"TopicListener|{topic}|201|error201", f"user_uuid: {user_uuid}, log_time: {log_time}")
         return
 
     # --- fill log_list ---
@@ -249,7 +253,6 @@ def method_c001(_client, _userdata, message):
     ]
 
     # --- get ---
-    topic = _client.casper_info.get('topic')
     last_log_key = topic_info_dict.get(topic)
 
     # --- check ---
@@ -262,7 +265,7 @@ def method_c001(_client, _userdata, message):
     topic_info_dict[topic] = log_key
 
     # --- save ---
-    # methods.debug_log(f"TopicListener|158", f"#log_list: {log_list}")
+    # methods.debug_log(f"TopicListener|{topic}|268", f"#log_list: {log_list}")
     log_file_path = os.path.join(Global.save_dir, f'{log_uuid}.log')
     methods.write_text(log_file_path, ' | '.join(log_list) + '\n', 'a')
 
@@ -271,17 +274,16 @@ class TopicListener:
     """
     """
 
-
     def __init__(self, subscribe_topic, method_name):
         self.subscribe_topic = subscribe_topic
         self.method_name = method_name
 
     def subscribe(self):
 
-
+        # --- define ---
         topic_info_dict[self.subscribe_topic] = str()
-        
 
+        # --- set ---
         if self.method_name == 'method_v001':
             method = method_v001
         elif self.method_name == 'method_c001':
@@ -289,7 +291,7 @@ class TopicListener:
         else:
             method = None
 
-
+        # --- start ---
         client = Global.emqx_factory.Client(host=Global.emqx_host, port=Global.emqx_port)
         client.casper_info = {
             'topic': self.subscribe_topic

+ 31 - 1
sri-server-bg03/lib/Connection_e1.py

@@ -49,6 +49,16 @@ class SRIConnection(asyncio.Protocol):
         self.update_at = methods.now_ts()
         clients[self.connection_id] = self
 
+        # --- get VehicleStatus ---
+        unique_dict = {'name': 'VehicleStatus'}
+        item = Global.mdb.get_one('GlobalVariable', unique_dict)
+        data = item.get('args', {})
+
+        # --- set VehicleStatus ---
+        data[str(self.connection_id)] = 2
+        update_dict = {'args': data}
+        Global.mdb.update_one('GlobalVariable', unique_dict, update_dict)
+
         # 获取底层 socket
         # sock = self.client.get_extra_info('socket')
 
@@ -65,6 +75,16 @@ class SRIConnection(asyncio.Protocol):
         methods.debug_log(f"{self.connection_id}|SRIConnection|65", f"连接已关闭")
         methods.debug_log(f"{self.connection_id}|SRIConnection|65", f"clients: len{clients}")
 
+        # --- get VehicleStatus ---
+        unique_dict = {'name': 'VehicleStatus'}
+        item = Global.mdb.get_one('GlobalVariable', unique_dict)
+        data = item.get('args', {})
+
+        # --- set VehicleStatus ---
+        data[str(self.connection_id)] = 1
+        update_dict = {'args': data}
+        Global.mdb.update_one('GlobalVariable', unique_dict, update_dict)
+
         # --- 处理车端掉线,通知所有舱端
         if self.client_type == 'vehicle':
             """
@@ -80,7 +100,7 @@ class SRIConnection(asyncio.Protocol):
             re_head_data = struct.pack(self.head_sequence, re_command_id, re_body_length)
             re_body_data = o2.SerializeToString()
             re_send_data = re_head_data + re_body_data
-            methods.debug_log(f"{self.connection_id}|SRIConnection085", f"re_command_id: {re_command_id}")
+            methods.debug_log(f"{self.connection_id}|SRIConnection102", f"re_command_id: {re_command_id}")
             for item in clients.values():
                 if item.client_type == 'cockpit':
                     item.client.write(re_send_data)
@@ -483,6 +503,16 @@ class SRIConnection(asyncio.Protocol):
                 methods.debug_log(f"{self.connection_id}|SRIConnection428", f"#index: {o1.index}")
                 item.client.write(re_send_data)
 
+        # --- get VehicleStatus ---
+        unique_dict = {'name': 'VehicleStatus'}
+        item = Global.mdb.get_one('GlobalVariable', unique_dict)
+        data = item.get('args', {})
+
+        # --- set VehicleStatus ---
+        data[str(self.connection_id)] = 4
+        update_dict = {'args': data}
+        Global.mdb.update_one('GlobalVariable', unique_dict, update_dict)
+
     def message2006(self, body_data):
 
         # --- 解析消息体