read map from config file

This commit is contained in:
quantulr
2024-01-30 17:25:58 +08:00
parent 4e62811f16
commit fca55c5cb8
12 changed files with 46 additions and 114 deletions

Binary file not shown.

View File

@ -1,10 +1,8 @@
import asyncio
import json import json
from typing import Dict
from redis import asyncio as aioredis from redis import asyncio as aioredis
import uvicorn import uvicorn
from fastapi import FastAPI, BackgroundTasks, UploadFile from fastapi import FastAPI, BackgroundTasks
app = FastAPI() app = FastAPI()
@ -27,7 +25,7 @@ async def event_rcv(data: dict, background_tasks: BackgroundTasks):
def run_app(): def run_app():
uvicorn.run("main:app", host="0.0.0.0", port=8000) uvicorn.run(app=app, host="0.0.0.0", port=8000)
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -1,15 +0,0 @@
device_map = {
"192.168.1.12": "4GB-供油站",
"192.168.1.13": "T2变电所",
"192.168.1.14": "二厂平台~西",
"192.168.1.15": "二厂平台~中o1",
"192.168.1.16": "T1变电所",
"192.168.1.17": "二厂平台~东",
"192.168.1.18": "二厂平台~中o2",
"192.168.1.19": "T3变电所",
"192.168.1.20": "T11变电所",
"192.168.1.21": "4GA-供油站",
"192.168.1.22": "T9-变压器",
"192.168.1.23": "T6-变压器",
"192.168.1.24": "4DB-供油站",
}

View File

@ -1,4 +1,4 @@
mapping = { event_map = {
131329: '视频丢失', 131329: '视频丢失',
131330: '视频遮挡', 131330: '视频遮挡',
131331: '移动侦测', 131331: '移动侦测',

View File

@ -1,17 +0,0 @@
user_map = {
"192.168.1.12": [
],
"192.168.1.13": [],
"192.168.1.14": [],
"192.168.1.15": [],
"192.168.1.16": [],
"192.168.1.17": [],
"192.168.1.18": [],
"192.168.1.19": [],
"192.168.1.20": [],
"192.168.1.21": [],
"192.168.1.22": [],
"192.168.1.23": [],
"192.168.1.24": [],
}

View File

@ -1,82 +1,27 @@
import asyncio import asyncio
import json import json
from io import BytesIO from pathlib import Path
import requests import yaml
from custom_exception import FeishuAuthException
from mapping.event_map_mapping import mapping
from mapping.device_map import device_map
from mapping.user_map import user_map
from hik_push.mapping.event_map import event_map
from redis import asyncio as aioredis from redis import asyncio as aioredis
app_id = "cli_a525f3d78e3e500c"
app_secret = "JVhnbKfXifddjHVwcTqbEfn1rDQBYqDD"
headers = {"Authorization": ""}
def get_access_token(api_id, secret):
url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
data = {
"app_id": api_id,
"app_secret": secret
}
resp = requests.post(url, data=data).content.decode('utf-8')
return json.loads(resp)['tenant_access_token']
# 获取事件的图片
def get_image_url(event):
analysis_key = mapping.get(event['eventType'])['detection_key']
if analysis_key is None:
return None
images = []
for el in event['data'][analysis_key]:
images.append(el['imageUrl'])
if len(images) == 0:
return None
return images
def get_value_by_nested_key(my_dict, nested_key):
ret = my_dict
for key in nested_key:
ret = ret[key]
return ret
# 上次图片到飞书
def upload_image(url):
image_content = requests.get(url).content
payload = {'image_type': 'message'}
files = [
('image', ('file', BytesIO(image_content), 'application/octet-stream'))
]
image = requests.request("POST", "https://open.feishu.cn/open-apis/im/v1/images", data=payload,
files=files, headers=headers).content.decode('utf-8')
data = json.loads(image)
code = data['code']
if code == 99991663:
raise FeishuAuthException
image_key = json.loads(image)['data']['image_key']
return image_key
# 推送到飞书
def push_to_feishu(data):
push_url = "https://open.feishu.cn/open-apis/message/v4/batch_send/"
data = json.dumps(data)
r = requests.post(push_url, data=data, headers=headers).content.decode('utf-8')
data = json.loads(r)
code = data['code']
if code == 99991663:
raise FeishuAuthException
print(r)
async def read_event(): async def read_event():
# 读取配置文件
home_dir = Path.home()
with open(home_dir / '.config' / 'hik-push' / 'config.yaml', 'r', encoding='utf-8') as f:
config = yaml.safe_load(f)
if "user_ids" not in config:
print("请配置user_ids")
return
if "devices" not in config:
print("请配置devices")
return
print(config)
user_map = config['user_ids']
device_map = config['devices']
redis_client = await aioredis.Redis(host="127.0.0.1", port=6379) redis_client = await aioredis.Redis(host="127.0.0.1", port=6379)
while True: while True:
data = await redis_client.brpop("hik-sub-event") data = await redis_client.brpop("hik-sub-event")
@ -86,7 +31,7 @@ async def read_event():
for event in events: for event in events:
# 将eventType ID 替换为中文字符串 # 将eventType ID 替换为中文字符串
event_type = event['eventType'] event_type = event['eventType']
event_type_str = mapping.get(event_type, "未知事件类型") event_type_str = event_map.get(event_type, "未知事件类型")
event['eventType'] = event_type_str event['eventType'] = event_type_str
if "data" in event: if "data" in event:
# 如果存在 data 属性 # 如果存在 data 属性
@ -112,7 +57,12 @@ async def read_event():
except Exception as e: except Exception as e:
print("error: ", e) print("error: ", e)
continue continue
await asyncio.sleep(0.5) finally:
await asyncio.sleep(0.5)
def run_app():
asyncio.run(read_event())
if __name__ == "__main__": if __name__ == "__main__":

18
poetry.lock generated
View File

@ -31,6 +31,17 @@ doc = ["Sphinx (>=7)", "packaging", "sphinx-autodoc-typehints (>=1.2.0)", "sphin
test = ["anyio[trio]", "coverage[toml] (>=7)", "exceptiongroup (>=1.2.0)", "hypothesis (>=4.0)", "psutil (>=5.9)", "pytest (>=7.0)", "pytest-mock (>=3.6.1)", "trustme", "uvloop (>=0.17)"] test = ["anyio[trio]", "coverage[toml] (>=7)", "exceptiongroup (>=1.2.0)", "hypothesis (>=4.0)", "psutil (>=5.9)", "pytest (>=7.0)", "pytest-mock (>=3.6.1)", "trustme", "uvloop (>=0.17)"]
trio = ["trio (>=0.23)"] trio = ["trio (>=0.23)"]
[[package]]
name = "async-timeout"
version = "4.0.3"
description = "Timeout context manager for asyncio programs"
optional = false
python-versions = ">=3.7"
files = [
{file = "async-timeout-4.0.3.tar.gz", hash = "sha256:4640d96be84d82d02ed59ea2b7105a0f7b33abe8703703cd0ab0bf87c427522f"},
{file = "async_timeout-4.0.3-py3-none-any.whl", hash = "sha256:7405140ff1230c310e51dc27b3145b9092d659ce68ff733fb0cefe3ee42be028"},
]
[[package]] [[package]]
name = "certifi" name = "certifi"
version = "2023.11.17" version = "2023.11.17"
@ -768,6 +779,9 @@ files = [
{file = "redis-5.0.1.tar.gz", hash = "sha256:0dab495cd5753069d3bc650a0dde8a8f9edde16fc5691b689a566eda58100d0f"}, {file = "redis-5.0.1.tar.gz", hash = "sha256:0dab495cd5753069d3bc650a0dde8a8f9edde16fc5691b689a566eda58100d0f"},
] ]
[package.dependencies]
async-timeout = {version = ">=4.0.2", markers = "python_full_version <= \"3.11.2\""}
[package.extras] [package.extras]
hiredis = ["hiredis (>=1.0.0)"] hiredis = ["hiredis (>=1.0.0)"]
ocsp = ["cryptography (>=36.0.1)", "pyopenssl (==20.0.1)", "requests (>=2.26.0)"] ocsp = ["cryptography (>=36.0.1)", "pyopenssl (==20.0.1)", "requests (>=2.26.0)"]
@ -1161,5 +1175,5 @@ files = [
[metadata] [metadata]
lock-version = "2.0" lock-version = "2.0"
python-versions = "^3.12" python-versions = ">=3.11"
content-hash = "00976ed3a44ab76661d8b7e8a5c2a90a324be8dda00b9467ef57a5a8ee139489" content-hash = "9cd979c9426ddc879502c540f0abfc73c4e970e206a58ccf29df4abe53c98e9a"

View File

@ -6,10 +6,11 @@ authors = ["quantulr <35954003+quantulr@users.noreply.github.com>"]
readme = "README.md" readme = "README.md"
[tool.poetry.dependencies] [tool.poetry.dependencies]
python = "^3.12" python = ">=3.11"
fastapi = { extras = ["all"], version = "^0.109.0" } fastapi = { extras = ["all"], version = "^0.109.0" }
redis = "^5.0.1" redis = "^5.0.1"
requests = "^2.31.0" requests = "^2.31.0"
pyyaml = "^6.0.1"
[build-system] [build-system]
@ -18,4 +19,5 @@ build-backend = "poetry.core.masonry.api"
[tool.poetry.scripts] [tool.poetry.scripts]
hik-push = 'hik_push.main:run_app' hik-sub = 'hik_push.main:run_app'
hik-push = 'hik_push.read_event:run_app'