Files
lnrt-mqtt/upload_pict_mom.py
2025-09-15 15:45:57 +08:00

68 lines
2.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
import time
import json
import requests
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
# 加载配置
with open("config_mom.json", encoding="utf-8") as f:
config = json.load(f)
MOM_UPLOAD_URL = f"{config['mom_prefix']}/cams-service/openapi/hotwater/file/upload"
OPNO = config["opNo"]
WATCH_FOLDERS = config["watch_folders"]
def extract_sn(filename: str) -> str:
"""取文件名前 22 位作为 SN不足 22 位则整个文件名返回"""
name, _ = os.path.splitext(filename) # 去掉扩展名
return name[:22]
def upload_image(file_path: str) -> None:
filename = os.path.basename(file_path)
sn = extract_sn(filename)
# 构造三个独立的 multipart 字段
multipart_fields = {
"opNo": (None, OPNO), # 普通文本字段
"sn": (None, sn), # 普通文本字段
"file": (filename, open(file_path, "rb"), "image/jpeg")
}
try:
resp = requests.post(
MOM_UPLOAD_URL,
files=multipart_fields,
timeout=30
)
print(f"[上传] {filename}{resp.status_code} {resp.text}")
except Exception as e:
print(f"[上传失败] {filename}{e}")
class ImageHandler(FileSystemEventHandler):
def on_created(self, event):
if not event.is_directory:
ext = os.path.splitext(event.src_path)[1].lower()
time.sleep(0.5) # 等待文件写完
upload_image(event.src_path)
if __name__ == "__main__":
for folder in WATCH_FOLDERS:
os.makedirs(folder, exist_ok=True)
event_handler = ImageHandler()
observer = Observer()
for folder in WATCH_FOLDERS:
observer.schedule(event_handler, folder, recursive=False)
print(f"[监控启动] {os.path.abspath(folder)}")
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()