diff --git a/app/api/v1/endpoints/events.py b/app/api/v1/endpoints/events.py index 402a34f..cd70ab5 100644 --- a/app/api/v1/endpoints/events.py +++ b/app/api/v1/endpoints/events.py @@ -182,6 +182,15 @@ async def handle_ocr_alert( return BaseResponse(code=200, msg="success") return BaseResponse(code=500, msg="fail to update data") +# 获取消息的统计数据 +@router.get("/events/stMessages/{day}", ) +async def get_messages_st( + day: int, + db: AsyncSession = Depends(get_db), +): + data = await event.get_messages_st(db, day) + return BaseResponse(code=200, msg="success", data=data) + # 查看告警详情 @router.get("/events/alert/{messageId}", response_model=BaseResponse[OcrAlertMessage]) diff --git a/app/config/config.yaml b/app/config/config.yaml index 4fdf236..d5dd5a6 100644 --- a/app/config/config.yaml +++ b/app/config/config.yaml @@ -7,6 +7,13 @@ kangda: deviceId: pc lang: zh_CN +kangda_front: + account: "rbsstaff1" + password: "123456" + userType: "2" + crc: "0f007401b091" + lang : "zh_CN" + ws: url: rest.concoai.com/imserver/ account: rbsstaff1 @@ -16,6 +23,13 @@ url_login : "http://erpapi.concoai.com/basis-api/user/login" url_event_list : "http://erpapi.concoai.com/robot/event/page" url_event_detail: "http://erpapi.concoai.com/robot/event/" +url_login_front : "https://rest.concoai.com/login" +url_groupy: "https://rest.concoai.com/robot/groupByDuty" +url_robot_video_list: "https://rest.concoai.com/robot/videoList" +url_robot_detail : "https://rest.concoai.com/robot/detail/" +url_robot_event_info : "https://rest.concoai.com/event/robotEventInfo" +url_robot_current_duty : "https://rest.concoai.com/robot/currentDuty/" + image_save_path: "imagesDownload" image_save_path_ocr: "imagesOcr" diff --git a/app/crud/event.py b/app/crud/event.py index e2a1806..f010e58 100644 --- a/app/crud/event.py +++ b/app/crud/event.py @@ -397,6 +397,23 @@ class CRUDEvent(CRUDBase[Event, EventUpdate, EventUpdate]): except Exception as e: print(f"{e}") + + async def get_messages_st( + self, + db: AsyncSession, + day: int + ): + try: + query_stmt = ( + select( + # Message.eventType, + func.count(Message.messageId)) + .group_by(Message.eventType) + ) + result = await db.execute(query_stmt) + return result.scalars() + except Exception as e: + print(f"{e}") diff --git a/app/models/models.py b/app/models/models.py index 74584bf..3f66236 100644 --- a/app/models/models.py +++ b/app/models/models.py @@ -153,7 +153,73 @@ class Robot(Base): status = Column(String(5), comment='机器人状态') createTime = Column(DateTime, default=datetime.now, nullable=False, comment='创建时间') updateTime = Column(DateTime, default=datetime.now, nullable=False, comment='更新时间') + + +# class RobotInfo(Base): +# __tablename__ = "robot_info" +# robotInfoId = Column() + +# hkStstusName = Column(String(20)) +# code = Column(String(5)) +# errorType = Column(String(5)) +# remoteControl = Column(String(5)) +# buttonStop = Column(String(5)) +# vertical = Column(String(5)) +# versionName = Column(String(50)) +# theta = Column(String(20)) +# speed = Column(String(5)) +# routeName = Column(String(20)) +# charingTaskStatus = Column(String(5)) +# socketType = Column(String(5)) +# horizontal = Column( String(5)) +# ststusName = Column(String(20)) +# enStstusName = Column(String(20)) +# aistatus = Column(String(5)) +# pm2_5 = Column(String(20)) +# temperature = Column(String(20)) +# humidity = Column(String(20)) +# power = Column(String(5)) +# floor = Column(String(5)) +# map = Column(String(20)) +# mileage = Column(String(5)) +# area = Column(String(5)) +# nextTaskTime = Column('nextTaskTime', String) +# address = Column('address', String) +# fromUserId = Column('fromUserId', String) +# ip = Column('ip', String) +# pm10 = Column('pm10', String) +# index = Column('index', String) # 使用引号避免关键字冲突 +# message = Column('message', String) +# robotId = Column('robotId', String) +# versionCode = Column('versionCode', String) +# videoStatus = Column('videoStatus', String) +# voltage = Column('voltage', String) +# focal = Column('focal', String) +# ststus = Column('ststus', String) +# positon = Column('positon', String) # 注意原始JSON中的拼写 +# robotType = Column('robotType', String) +# clearCharingTaskTime = Column('clearCharingTaskTime', String) +# cmd = Column('cmd', String) +# vehicleid = Column('vehicleid', String) +# device = Column('device', String) +# status = Column('status', String) + + +class Group(Base): + __tablename__ = "group" + groupingId = Column(String(100), primary_key=True, comment="分组id") + name = Column(String(20), comment="组名") + + # 后续可能要单独拆分一张表 + tenantInfoId = Column(String(100), comment="租户Id") - +# 组和机器人对应表 +class GroupRobot(Base): + __tablename__ = "group_robot" + + id = Column(BigInteger, primary_key=True, autoincrement=True, comment="id主键") + groupingId = Column(String(100), ForeignKey('group.groupingId', ondelete="CASCADE"),comment='分组ID') + robotId = Column(String(100), ForeignKey("robot.robotId", ondelete="CASCADE"), comment='机器人ID') + \ No newline at end of file diff --git a/app/services/event_sync_service.py b/app/services/event_sync_service.py index 6c5c81b..d5051a3 100644 --- a/app/services/event_sync_service.py +++ b/app/services/event_sync_service.py @@ -3,7 +3,7 @@ from datetime import datetime from telnetlib import AYT from tkinter import W from typing import List, Dict, Any -from sqlalchemy import select +from sqlalchemy import select, update from sqlalchemy.ext.asyncio import AsyncSession from app.core.database import async_session from app.models.models import Event, Image, Temperature, Message, Robot @@ -88,12 +88,12 @@ class EventSyncService: """更新机器人在线状态""" try: async with async_session() as session: - update = ( + update_stmt = ( update(Robot).where(Robot.robotId == robot.robotId).values( onlineStatus = robot.onlineStatus ) ) - await session.execute(update) + await session.execute(update_stmt) await session.commit() except Exception as e: print(f"更新机器人在线状态失败: {e}") diff --git a/app/services/websocket_service.py b/app/services/websocket_service.py index 8988916..7f7b349 100644 --- a/app/services/websocket_service.py +++ b/app/services/websocket_service.py @@ -126,7 +126,7 @@ class WebSocketClient: try: # 接收消息 message = await websocket.recv() - print(f"{datetime.now()}收到消息: {message[:100]}...") # 只打印前100个字符 + print(f"{datetime.now()}收到消息: {message}...") # 只打印前100个字符 # 处理消息 await self.process_message(message) diff --git a/app/util/kangda.py b/app/util/kangda.py index 7e0c484..68fa357 100644 --- a/app/util/kangda.py +++ b/app/util/kangda.py @@ -1,5 +1,6 @@ import re import os +from urllib import response import yaml import requests from app.util.status import TemperatureStatus @@ -149,6 +150,176 @@ class Kangda: except ValueError as e: print("解析JSON失败:", e) + def _login_front(self): + headers = { + "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36", + "accept-language": "zh-CN,zh;q=0.9", + "connections": "keep-alive", + "Host": "erpapi.concoai.com", + "accept-encoding": "gzip, deflate", + "upgrade-insecure-requests": "1", + "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7" + } + try: + response = requests.post( + url=self.config["url_login_front"], + json=self.config["kangda_front"], + headers=headers + ) + + # 检查请求是否成功 + response.raise_for_status() + result = response.json() + + return { + "tenantInfoId": result.get("data").get("tenantInfoId"), + "token": result.get("data").get("token") + } + + + except requests.exceptions.RequestException as e: + print("前端登录请求出错:", e) + except ValueError as e: + print("前端解析JSON失败:", e) + + # 获取机器人班组信息 + def _get_robot_current_duty(self, token, robotId): + + headers = { + "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36", + "accept-language": "zh-CN,zh;q=0.9", + "connections": "keep-alive", + "Host": "erpapi.concoai.com", + "accept-encoding": "gzip, deflate", + "upgrade-insecure-requests": "1", + "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7", + "Authorization": "Bearer "+token, + + } + + try: + response = requests.get( + url=self.config["url_robot_current_duty"] + robotId, + headers=headers + ) + + response.raise_for_status() + response = response.json() + + return response.get("data") + except requests.exceptions.RequestException as e: + print("获取机器人班组信息出错:", e) + except ValueError as e: + print("获取机器人班组信息解析JSON失败:", e) + + + # 获取机器人详情 + def _get_robot_detail(self, token, robotId): + + headers = { + "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36", + "accept-language": "zh-CN,zh;q=0.9", + "connections": "keep-alive", + "Host": "erpapi.concoai.com", + "accept-encoding": "gzip, deflate", + "upgrade-insecure-requests": "1", + "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7", + "Authorization": "Bearer "+token, + + } + + try: + response = requests.get( + url=self.config["url_robot_detail"] + robotId, + headers=headers + ) + + response.raise_for_status() + response = response.json() + + return response.get("data") + + except requests.exceptions.RequestException as e: + print("获取机器人详情出错:", e) + except ValueError as e: + print("获取机器人详情解析JSON失败:", e) + + # 根据groupingId 查看组内机器人videoList + def _get_robot_video_list(self, token, groupingIds): + + headers = { + "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36", + "accept-language": "zh-CN,zh;q=0.9", + "connections": "keep-alive", + "Host": "erpapi.concoai.com", + "accept-encoding": "gzip, deflate", + "upgrade-insecure-requests": "1", + "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7", + "Authorization": "Bearer "+token, + + } + + try: + response = requests.post( + url=self.config["url_robot_video_list"], + json = { + "groupingIds":groupingIds + }, + headers=headers + ) + + response.raise_for_status() + response = response.json() + + # 返回video_list + return response.get("data") + + except requests.exceptions.RequestException as e: + print("获取video_list出错:", e) + except ValueError as e: + print("获取video_listJSON失败:", e) + + # 查看租户名下所有分组 + def _get_robot_group(self, tenantInfoId, token): + # 请求头 + headers = { + "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36", + "accept-language": "zh-CN,zh;q=0.9", + "connections": "keep-alive", + "Host": "erpapi.concoai.com", + "accept-encoding": "gzip, deflate", + "upgrade-insecure-requests": "1", + "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7", + "Authorization": "Bearer "+token, + + } + + try: + response = requests.post( + url=self.config["url_groupy"], + json={ + "tenantInfoId": tenantInfoId + }, + headers=headers + ) + + response.raise_for_status() + + response = response.json() + + # 返回租户名下的任务列表 + return response.get("data").get("dutyList") + + # print(response) + + except requests.exceptions.RequestException as e: + print("查询分组出错:", e) + except ValueError as e: + print("查询分组解析JSON失败:", e) + + + + def _download_image(self, url, save_image=True): ''' @@ -225,6 +396,7 @@ class Kangda: return TemperatureStatus.NORMAL + diff --git a/test_t.py b/test_t.py index 6616569..2e848b6 100644 --- a/test_t.py +++ b/test_t.py @@ -6,16 +6,30 @@ from app.util.baiduOcr import BadiduOcr # #-----------------------测试获取kangda接口事件列表-------------------------------- -# kangda = Kangda() +kangda = Kangda() # print(kangda.get_event_list()) # #-----------------------测试获取kangda接口事件列表end--------------------------- -#-------------------------测试百度ocr--------------------------------------------- -ocr = BadiduOcr() -result = ocr.image_inference("/home/admin-root/haotian/康达瑞贝斯/imagesKangda/0a7f94b11153fc79ef2dd8b18f9eb8ec.jpeg" - , True, True) +# #-------------------------测试百度ocr--------------------------------------------- +# ocr = BadiduOcr() +# result = ocr.image_inference("/home/admin-root/haotian/康达瑞贝斯/imagesKangda/0a7f94b11153fc79ef2dd8b18f9eb8ec.jpeg" +# , True, True) -#-------------------------测试百度ocrend----------------------------------------- +# #-------------------------测试百度ocrend----------------------------------------- + + +#---------------------------测试康达前端登录----------------------------------------- +d = kangda._login_front() +# duty_list = kangda._get_robot_group(d["tenantInfoId"], d["token"]) +# for duty in duty_list: +# video_list = kangda._get_robot_video_list(d["token"], duty["groupingId"]) +# print(duty_list) + +# robot_detail = kangda._get_robot_detail(d["token"], "6865c4ce61ee45a69e79f62eee55b83c") + +current_duty = kangda._get_robot_current_duty(d["token"], "6865c4ce61ee45a69e79f62eee55b83c") +print(current_duty) +#---------------------------测试康达前端登录end--------------------------------------