This commit is contained in:
quantulr
2024-01-24 16:15:00 +08:00
parent fcd4bb2d9d
commit 4b4ee17bc7
10 changed files with 348 additions and 26 deletions

Binary file not shown.

View File

@ -0,0 +1,45 @@
mapping = {
131329: {"type": '视频丢失', "analyze_key": None},
131330: {"type": '视频遮挡', "analyze_key": None},
131331: {"type": '移动侦测', "analyze_key": None},
131612: {"type": '场景变更', "analyze_key": None},
131613: {"type": '虚焦', "analyze_key": None},
589825: {"type": '报警输入', "analyze_key": None},
196355: {"type": '可视域事件', "analyze_key": None},
851969: {"type": 'GPS采集', "analyze_key": None},
131588: {"type": '区域入侵', "analyze_key": "fielddetection"},
131585: {"type": '越界侦测', "analyze_key": "linedetection"},
131586: {"type": '进入区域', "analyze_key": "regionEntrance"},
131587: {"type": '离开区域', "analyze_key": "regionExiting"},
131590: {"type": '徘徊侦测', "analyze_key": "loitering"},
131593: {"type": '人员聚集', "analyze_key": "group"},
131592: {"type": '快速移动', "analyze_key": "rapidMove"},
131591: {"type": '停车侦测', "analyze_key": "parking"},
131594: {"type": '物品遗留', "analyze_key": "unattendedBaggage"},
131595: {"type": '物品拿取', "analyze_key": "attendedBaggage"},
131664: {"type": '人数异常', "analyze_key": "peoplenumChange"},
131665: {"type": '间距异常', "analyze_key": "spacingChange"},
131596: {"type": '剧烈运动', "analyze_key": "violentMotion"},
131603: {"type": '岗位值守', "analyze_key": "leavePosition"},
131605: {"type": '倒地', "analyze_key": "fallDown"},
131597: {"type": '攀高', "analyze_key": "reachHight"},
131666: {"type": '人员站立', "analyze_key": "standUp"},
131609: {"type": '防风场滞留', "analyze_key": "yardTarry"},
131598: {"type": '起身', "analyze_key": "getUp"},
131599: {"type": '人靠近ATM', "analyze_key": "humanEnter"},
131600: {"type": '操作超时', "analyze_key": "overTime"},
131601: {"type": '贴纸条', "analyze_key": "stickUp"},
131602: {"type": '安装读卡器', "analyze_key": "installScanner"},
131604: {"type": '尾随', "analyze_key": "trail"},
131606: {"type": '声强突变', "analyze_key": "audioAbnormal"},
131607: {"type": '折线攀高', "analyze_key": "advReachHeight"},
131611: {"type": '折线警戒面', "analyze_key": "advTraversePlane"},
192518: {"type": '温差报警', "analyze_key": "thermometryDiff"},
192517: {"type": '温度报警', "analyze_key": "thermometry"},
192516: {"type": '船只检测', "analyze_key": "shipDetection"},
192515: {"type": '火点检测', "analyze_key": "fireDetection"},
192514: {"type": '烟火检测', "analyze_key": "smokeAndFireDetection"},
192513: {"type": '烟雾检测', "analyze_key": "smokeDetection"},
930335: {"type": '高空抛物', "analyze_key": None},
889196545: {"type": '监控点离线', "analyze_key": None},
}

View File

@ -4,17 +4,24 @@ from typing import Dict
from redis import asyncio as aioredis
import uvicorn
from fastapi import FastAPI, BackgroundTasks
from fastapi import FastAPI, BackgroundTasks, UploadFile
app = FastAPI()
async def add_stream(data: dict):
redis = await aioredis.from_url("redis://localhost", db=0)
await redis.xadd("hik-event", {"event": json.dumps(data)})
await redis.lpush("event", json.dumps(data))
# await redis.xadd("hik-event", {"event": json.dumps(data)})
await redis.close()
@app.post("/upload")
async def upload_file(file: UploadFile):
print(file)
return {"message": "success"}
@app.get("/")
async def root():
return {"message": "Hello World"}
@ -26,29 +33,6 @@ async def event_rcv(data: dict, background_tasks: BackgroundTasks):
return {"data": data}
@app.on_event("startup")
async def background_task():
redis = await aioredis.from_url("redis://localhost", db=0)
# await redis.xgroup_create(groupname="consumer-group", name="hik-event", mkstream=True)
while True:
# result = await redis.xread(streams={"hik-event": 0})
result = await redis.xreadgroup(groupname="consumer-group", consumername="consumer",
streams={"hik-event": 0},
)
print(result)
if len(result[0][1]) == 0:
print("wuyou")
# await redis.close()
continue
id = result[0][1][0][0].decode("utf-8")
await redis.xack("hik-event", "consumer-group", id)
# print(result[0][1][0][0].decode("utf-8"))
print(result[0][1][0][1][b'event'].decode("utf-8"))
await asyncio.sleep(1)
await redis.close()
def run_app():
uvicorn.run("main:app", host="0.0.0.0", port=8000)

136
hik_push/read_event.py Normal file
View File

@ -0,0 +1,136 @@
import asyncio
import json
from io import BytesIO
import requests
from event_map_mapping import mapping
from redis import asyncio as aioredis
headers = {"Authorization": "Bearer t-g1041oeFF3LTS5MA3HQYUHYFOK246EAEPFJWPRWP"}
# 获取事件的图片
def get_image_url(event):
analysis_key = mapping.get(event['eventType'])['analyze_key']
print(analysis_key)
if analysis_key is None:
return []
images = []
for el in event['data'][analysis_key]:
images.append(el['imageUrl'])
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')
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/"
# push_url = "http://192.168.20.115:8000/ipaasuat/engine_company/anycross/trigger/callback/MmRhZTE4OTRiYjVkZDQ5YWNmOGRmZDI0NjQ1MTBlODUw/1.0.0"
data = json.dumps(data)
r = requests.post(push_url, data=data, headers=headers).content.decode('utf-8')
print(r)
async def read_event():
redis_client = await aioredis.from_url("redis://localhost")
while True:
data = await redis_client.brpop("event")
event_json = json.loads(data[1].decode('utf-8'))
try:
events = event_json["params"]["events"]
for event in events:
event_type = mapping.get(event['eventType'], {"type": "未知事件类型"})
print(event_type)
# TODO: 上传图片到飞书链接
images = get_image_url(event)
feishu_image_url = upload_image(images[0])
print(feishu_image_url)
# TODO: 根据ip_address获取对应userid
#
ip_address = event["data"]["ipAddress"]
# channel_name = get_value_by_nested_key(event, ("data", "channelName"))
# TODO: 向飞书推送消息
push_data = {
"user_ids": [
"8dg79c18"
],
"msg_type": "interactive",
"card": {
"config": {
"wide_screen_mode": True
},
"elements": [
{
"tag": "markdown",
"content": "这里是卡片文本支持使用markdown标签设置文本格式。例如\n*斜体* 、**粗体**、~~删除线~~、[文字链接](https://www.feishu.cn)、<at id=all></at>、<font color='red'> 彩色文本 </font>"
},
{
"alt": {
"content": "",
"tag": "plain_text"
},
"img_key": feishu_image_url,
"tag": "img",
"mode": "fit_horizontal",
"compact_width": False
},
{
"tag": "action",
"actions": [
{
"tag": "button",
"text": {
"tag": "plain_text",
"content": "这是跳转按钮"
},
"type": "primary",
"url": "https://feishu.cn"
}
]
}
],
"header": {
"template": "blue",
"title": {
"content": event_type["type"],
"tag": "plain_text"
}
}
}
}
push_to_feishu(push_data)
print(event_type["type"], ip_address)
except Exception as e:
print("error: ", e)
continue
# except Exception as e:
# print("error", e)
# # await redis_client.lpush("event", json.dumps(event_json))
# continue
if __name__ == "__main__":
asyncio.run(read_event())

BIN
hik_push/temp.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 MiB

14
hik_push/test.py Normal file
View File

@ -0,0 +1,14 @@
import io
import json
import requests
if __name__ == '__main__':
image_content = requests.get(
"http://47.102.206.10:8086/api/uploads/image/20231101/5bedf085-841a-48cc-bca2-9c9b2c751b48.jpeg").content
image_bytes = io.BytesIO(image_content)
# files = {"file": image_bytes}
data = {"file": "67tgby6y67tg", "file_bytes": "fsfadfsdffadf"}
resp = requests.post("http://localhost:8000/upload",
files={"file": image_bytes}).content.decode('utf-8')
print(resp)